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.
本题要求在常熟时间内完成next()操作,并且在tree的高度的空间复杂度。思路是和之前的Binary Tree Inorder Traverse一样的,采用前序遍历的思路,因为受到存储的限制,因此只有一次存储一个DFS,代码如下:
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> stack = new Stack<TreeNode>(); 13 public BSTIterator(TreeNode root) { 14 TreeNode node = root; 15 while(node!=null){ 16 stack.push(node); 17 node = node.left; 18 } 19 } 20 21 /** @return whether we have a next smallest number */ 22 public boolean hasNext() { 23 return !stack.isEmpty(); 24 } 25 26 /** @return the next smallest number */ 27 public int next() { 28 TreeNode tmp = stack.pop(); 29 int value = tmp.val; 30 tmp = tmp.right; 31 while(tmp!=null){ 32 stack.push(tmp); 33 tmp = tmp.left; 34 } 35 return value; 36 } 37 } 38 39 /** 40 * Your BSTIterator will be called like this: 41 * BSTIterator i = new BSTIterator(root); 42 * while (i.hasNext()) v[f()] = i.next(); 43 */