1. 程式人生 > >【python/leetcode/M】Binary Search Tree Iterator

【python/leetcode/M】Binary Search Tree Iterator

題目

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.

實現思路

要找到二叉搜尋樹中的最小節點,應該從根節點遞迴遍歷左節點,直到遍歷的節點沒有左節點,那麼該節點就是二叉樹中的最小節點。現在已經有二叉搜尋樹中沒有訪問過的最小節點了,那麼當訪問了該節點後,剩餘沒有訪問的樹中最小的節點在哪裡呢?如果該節點有右子樹,那麼在它的右子樹中(又回到了找一棵二叉搜尋樹的最小元素,不過這棵二叉搜尋樹變小了);如果沒有右子樹,那麼就是它的父節點。

為了能夠快速定位到父節點,我們可以用棧將遍歷路徑暫存起來,當進行next()操作時,我們彈出棧頂元素並進行訪問,如果它有右子樹的話就遍歷它的右子樹;如果沒有右子樹,當下次出棧操作時就是訪問當前節點的父節點了。

實現程式碼

# 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._pushLeft(root) def hasNext(self): """ :rtype: bool """ return self.stack def next(self): """ :rtype: int """ node = self.stack.pop() self._pushLeft(node.right) return node.val def _pushLeft(self,node): while node: self.stack.append(node) node = node.left # Your BSTIterator will be called like this: # i, v = BSTIterator(root), [] # while i.hasNext(): v.append(i.next())