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.

分析

考察非递归的中序遍历。这道题本质上是写一个二叉树的中序遍历的迭代器。内部设置一个栈,初始化的时候,存储从根节点到最左叶子节点的路径。在遍历的过程中,每次从栈中弹出一个元素,作为当前的返回结果,同时探测一下当前节点是否存在右孩子,如果有,则进入右孩子,并把从该右孩子到最左叶子节点的所有节点入栈。

代码

  1. // Binary Search Tree Iterator
  2. public class BSTIterator {
  3. public BSTIterator(TreeNode root) {
  4. stack = new Stack<>();
  5. while (root != null) {
  6. stack.push(root);
  7. root = root.left;
  8. }
  9. }
  10. /** @return whether we have a next smallest number */
  11. public boolean hasNext() {
  12. return !stack.isEmpty();
  13. }
  14. /** @return the next smallest number */
  15. public int next() {
  16. final TreeNode node = stack.pop();
  17. if (node.right != null) {
  18. TreeNode p = node.right;
  19. while (p != null) {
  20. stack.push(p);
  21. p = p.left;
  22. }
  23. }
  24. return node.val;
  25. }
  26. private Stack<TreeNode> stack;
  27. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/binary-tree/traversal/binary-search-tree-iterator.html