Leetcode: Binary Search Tree Iterator

来源:互联网 发布:协作机器人 知乎 编辑:程序博客网 时间:2024/06/06 18:37

Get idea from 西施豆腐渣 csdn.


Question

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Show Tags
Show Similar Problems


Analysis

It is the level order traversal.


Solution

# Definition for a  binary tree node# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass BSTIterator(object):    def __init__(self, root):        """        :type root: TreeNode        """        self.node = root        self.stack = []        return None    def hasNext(self):        """        :rtype: bool        """        if self.node!=None or len(self.stack)!=0:            return True    def next(self):        """        :rtype: int        """        if self.hasNext():            if self.node!=None:   # node maybe the right child, which is probably the None                while self.node!=None:                    self.stack = [self.node] + self.stack                    self.node = self.node.left                res = self.stack[0]                self.stack = self.stack[1:]                self.node = res.right            # move it forward to the right child, prepare for the next iteration            else:                res = self.stack[0]                self.stack = self.stack[1:]                self.node = res.right        return res.val# Your BSTIterator will be called like this:# i, v = BSTIterator(root), []# while i.hasNext(): v.append(i.next())
0 0
原创粉丝点击