首页 > 其他 > 详细

[Leetcode] Binary search tree --Binary Search Tree Iterator

时间:2018-01-08 14:42:17      阅读:193      评论:0      收藏:0      [点我收藏+]

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.

 

1)Solution:

Getting the next iterator is similarly to call  the generator in the python. for the next smallest number, it‘s like the inorder tree traversal printed out (sorted order). we use stack the store the node visited while using iterators

so the next could pop the node in order from stack.

 

 1     def __init__(self, root):
 2         """
 3         :type root: TreeNode
 4         """
 5         self.stk = []
 6         self.getAllLeftNode(root)
 7 
 8     def hasNext(self):
 9         """
10         :rtype: bool
11         """
12         
13         return (len(self.stk) != 0)
14 
15     def next(self):
16         """
17         :rtype: int
18         """
19         #pop from stack
20         node = self.stk.pop()
21         self.getAllLeftNode(node.right)
22         return node.val
23     
24     def getAllLeftNode(self, node):
25         ‘‘‘
26         get the most left nodes and put in the stack
27         ‘‘‘
28         while (node is not None):
29             self.stk.append(node)
30             node = node.left

 

[Leetcode] Binary search tree --Binary Search Tree Iterator

原文:https://www.cnblogs.com/anxin6699/p/8242225.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!