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.
Show Tags
Have you met this question in a real interview?
Yes
No
SOLUTION 1:
使用inorder traversal把tree转化为arraylist.
递归
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 ArrayList<TreeNode> list; 13 int index; 14 15 public BSTIterator(TreeNode root) { 16 list = new ArrayList<TreeNode>(); 17 iterator(root, list); 18 19 index = 0; 20 } 21 22 // solution 1: recursion. 23 public void dfs (TreeNode root, ArrayList<TreeNode> ret) { 24 if (root == null) { 25 return; 26 } 27 28 //Use inorder traversal. 29 dfs(root.left, ret); 30 ret.add(root); 31 dfs(root.right, ret); 32 } 33 34 35 /** @return whether we have a next smallest number */ 36 public boolean hasNext() { 37 if (index < list.size()) { 38 return true; 39 } 40 41 return false; 42 } 43 44 /** @return the next smallest number */ 45 public int next() { 46 return list.get(index++).val; 47 } 48 } 49 50 /** 51 * Your BSTIterator will be called like this: 52 * BSTIterator i = new BSTIterator(root); 53 * while (i.hasNext()) v[f()] = i.next(); 54 */