leetcode 173 二叉搜索树迭代器 模拟函数调用栈与程序计数器法

def inorder(root):
    if root.left:
        inorder(root.left)
    print(root.val)
    if root.right:
        inorder(root.right)
class BSTIterator:

    def __init__(self, root):
        self.stack = [(root, 2)]        

    def run(self):
        while self.stack:
            n, p = self.stack.pop()
            if p == 2:
                if n.left:
                    self.stack.append((n, 3))
                else:
                    self.stack.append((n, 4))
            elif p == 3:
                self.stack.append((n, 4))
                self.stack.append((n.left, 2))
            elif p == 4:
                self.stack.append((n, 5))
            elif p == 5:
                if n.right:
                    self.stack.append((n, 6))
                else:
                    self.stack.append((n, 7))
            elif p == 6:
                self.stack.append((n, 7))
                self.stack.append((n.right, 2))
            elif p == 7:
                pass
class BSTIterator:

    def __init__(self, root):
        self.stack = []
        if root:
            self.stack,append((root, 2))
            self.run_until_process()
        
    def run_until_process(self):
        while self.stack:
            n, p = self.stack.pop()
            if p == 2:
                if n.left:
                    self.stack.append((n, 3))
                else:
                    self.stack.append((n, 4))
            elif p == 3:
                self.stack.append((n, 4))
                self.stack.append((n.left, 2))
            elif p == 4:
                self.stack.append((n, 4))
                return
            elif p == 5:
                if n.right:
                    self.stack.append((n, 6))
                else:
                    self.stack.append((n, 7))
            elif p == 6:
                self.stack.append((n, 7))
                self.stack.append((n.right, 2))
            elif p == 7:
                pass
    
    def next(self):
        n, p = self.stack.pop()
        self.stack.append((n, 5))
        self.run_until_process()
        return n.val
    
    def hasNext(self):
        return self.stack != []

你可能感兴趣的:(leetcode 173 二叉搜索树迭代器 模拟函数调用栈与程序计数器法)