原题链接在这里:https://leetcode.com/problems/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.
与Inorder Successor in BST相似。
用一个stack把所有最左边的node压进 stack中。
判断hasNext()时就是看stack 是否为空.
next()返回stack顶部top元素,若是top有右子树,就把右子树的所有最左node压入stack中.
constructor time complexity: O(h).
hashNext time complexity: O(1).
next time complexity: O(h).
Space: O(h), stack 最大为树的高度。
AC Java:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 11 public class BSTIterator { 12 Stack<TreeNode> stk; 13 public BSTIterator(TreeNode root) { 14 stk = new Stack<TreeNode>(); 15 while(root != null){ 16 stk.push(root); 17 root = root.left; 18 } 19 } 20 21 /** @return whether we have a next smallest number */ 22 public boolean hasNext() { 23 return !stk.isEmpty(); 24 } 25 26 /** @return the next smallest number */ 27 public int next() { 28 if(hasNext()){ 29 TreeNode top = stk.pop(); 30 if(top.right != null){ 31 TreeNode rightLeft = top.right; 32 while(rightLeft != null){ 33 stk.push(rightLeft); 34 rightLeft = rightLeft.left; 35 } 36 } 37 return top.val; 38 } 39 return -1; 40 } 41 } 42 43 /** 44 * Your BSTIterator will be called like this: 45 * BSTIterator i = new BSTIterator(root); 46 * while (i.hasNext()) v[f()] = i.next(); 47 */