码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-01-08 14:47:56      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:type   from   most   post   ext   arch   pytho   iterator   sim   

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

标签:type   from   most   post   ext   arch   pytho   iterator   sim   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!