LeetCode 173 : 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.
來源: https://leetcode.com/problems/binary-search-tree-iterator/
問題描述:
實現一個二叉搜索樹(BST)的迭代器。你的迭代器會使用BST的根節點初始化。
調用next()會返回BST中下一個最小的數字。
注意:next()和hasNext()應該滿足平均O(1)時間複雜度和O(h)空間複雜度,其中h是樹的高度。
解題思路:
創建一個棧,從根節點開始,每次迭代地將根節點的左孩子壓入棧,直到左孩子爲空爲止。
調用next()方法時,彈出棧頂,如果被彈出的元素擁有右孩子,則以右孩子爲根,將其左孩子迭代壓棧。
這裏從 http://yuanhsh.iteye.com/blog/2173429 這篇文章這裏借了兩張圖,很好的講述瞭解題思路。
源代碼:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
private Stack<TreeNode> nodeStack;
public BSTIterator(TreeNode root) {
nodeStack = new Stack<TreeNode>();
while(null != root){
nodeStack.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !nodeStack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode node = nodeStack.pop();
int result = node.val;
if(null != node.right){
node = node.right;
while(null != node){
nodeStack.push(node);
node = node.left;
}
}
return result;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/