思路
非递归中序遍历二叉树 —> 用栈存储
1) 构造器 —> 将根结点的最左结点都压栈
2) hashNext() —> 等价于判断栈是否为空
3) next()
- 访问结点。
- 处理其右子树的结点。
实现
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */public class BSTIterator { private Stack<TreeNode> stack = new Stack<>(); public BSTIterator(TreeNode root) { TreeNode t = root; while(t != null) { stack.push(t); t = t.left; } } public int next() { TreeNode cur = stack.pop(); int value = cur.val; cur = cur.right; // 每次访问完一个node,将其右子树的左边孩子压栈 while (cur != null) { stack.push(cur); cur = cur.left; } // 返回当前结点值 return value; } public boolean hasNext() { // 等价于,判断栈是否为空 return !stack.isEmpty(); }}/** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */