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.

Solution:

  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. public class BSTIterator {
  11. Stack<TreeNode> stack = null;
  12. TreeNode current = null;
  13. public BSTIterator(TreeNode root) {
  14. current = root;
  15. stack = new Stack<TreeNode>();
  16. }
  17. /** @return whether we have a next smallest number */
  18. public boolean hasNext() {
  19. return !stack.isEmpty() || current != null;
  20. }
  21. /** @return the next smallest number */
  22. public int next() {
  23. while (current != null) {
  24. stack.push(current);
  25. current = current.left;
  26. }
  27. TreeNode t = stack.pop();
  28. current = t.right;
  29. return t.val;
  30. }
  31. }
  32. /**
  33. * Your BSTIterator will be called like this:
  34. * BSTIterator i = new BSTIterator(root);
  35. * while (i.hasNext()) v[f()] = i.next();
  36. */