美文网首页
173. Binary Search Tree Iterator

173. Binary Search Tree Iterator

作者: 阿团相信梦想都能实现 | 来源:发表于2016-09-20 09:43 被阅读0次
use stack to iteratively traverse binary tree in order 
left, root, right 

# Definition for a  binary tree node
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class BSTIterator(object):
    def __init__(self, root):
        """
        :type root: TreeNode
        """
        self.stack=[]
        self.cur=root
        
    def hasNext(self):
        """
        :rtype: bool
        """
        return self.stack or self.cur
        

    def next(self):
        """
        :rtype: int
        """
        while self.cur:
            self.stack.append(self.cur)
            self.cur=self.cur.left
        node=self.stack.pop()
        self.cur=node.right
        
        return node.val
        
            
        

# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())

相关文章

网友评论

      本文标题:173. Binary Search Tree Iterator

      本文链接:https://www.haomeiwen.com/subject/uxtoettx.html