思路

非递归中序遍历二叉树 —> 用栈存储

1) 构造器 —> 将根结点的最左结点都压栈

2) hashNext() —> 等价于判断栈是否为空

3) next()

  1. 访问结点。
  2. 处理其右子树的结点。
    • 将以右子树为根的最左结点都压栈。

实现

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. public class BSTIterator {
  17. private Stack<TreeNode> stack = new Stack<>();
  18. public BSTIterator(TreeNode root) {
  19. TreeNode t = root;
  20. while(t != null) {
  21. stack.push(t);
  22. t = t.left;
  23. }
  24. }
  25. public int next() {
  26. TreeNode cur = stack.pop();
  27. int value = cur.val;
  28. cur = cur.right;
  29. // 每次访问完一个node,将其右子树的左边孩子压栈
  30. while (cur != null) {
  31. stack.push(cur);
  32. cur = cur.left;
  33. }
  34. // 返回当前结点值
  35. return value;
  36. }
  37. public boolean hasNext() {
  38. // 等价于,判断栈是否为空
  39. return !stack.isEmpty();
  40. }
  41. }
  42. /**
  43. * Your BSTIterator object will be instantiated and called as such:
  44. * BSTIterator obj = new BSTIterator(root);
  45. * int param_1 = obj.next();
  46. * boolean param_2 = obj.hasNext();
  47. */