173. Binary Search Tree Iterator
Design an iterator over a binary search tree with the following rules:
- Elements are visited in ascending order (i.e. an in-order traversal)
next()
andhasNext()
queries run in O(1) time inaverage.
Example
For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]
10
/ \
1 11
\ \
6 12
分析:
把所有的node存在ArrayList,然后用一个指针指向第一个node.
1 public class BSTIterator { 2 Stack<TreeNode> stack; 3 4 public BSTIterator(TreeNode root) { 5 stack = new Stack<>(); 6 while (root != null) { 7 stack.push(root); 8 root = root.left; 9 } 10 } 11 12 public boolean hasNext() { 13 return !stack.isEmpty(); 14 } 15 16 public int next() { 17 if (!hasNext()) return -1; 18 19 TreeNode temp = stack.pop(); 20 TreeNode node = temp.right; 21 while (node != null) { 22 stack.push(node); 23 node = node.left; 24 } 25 return temp.val; 26 } 27 }