解法一:前序遍历递归
在构造函数中进行前序遍历递归,获取完整的二叉搜索树节点序列。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/class BSTIterator {List<Integer> list;int index = 0;public BSTIterator(TreeNode root) {list = new LinkedList<>();preOrder(root);}private void preOrder(TreeNode root) {if (root == null) {return;}if (root.left != null) {preOrder(root.left);}list.add(root.val);if (root.right != null) {preOrder(root.right);}}/*** @return the next smallest number*/public int next() {return list.get(index++);}/*** @return whether we have a next smallest number*/public boolean hasNext() {return index < list.size();}}/*** 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();*/
解法二:用栈模拟递归
用栈模拟递归的过程,这样可以自己控制遍历的开始和终止。
参考官方题解:https://leetcode-cn.com/problems/binary-search-tree-iterator/solution/er-cha-sou-suo-shu-die-dai-qi-by-leetcode/
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/class BSTIterator {Deque<TreeNode> stack;public BSTIterator(TreeNode root) {stack = new LinkedList<>();leftOrder(root);}private void leftOrder(TreeNode root) {if (root == null) {return;}stack.push(root);if (root.left != null) {leftOrder(root.left);}}/*** @return the next smallest number*/public int next() {TreeNode nextNode = stack.pop();if (nextNode.right != null) {leftOrder(nextNode.right);}return nextNode.val;}/*** @return whether we have a next smallest number*/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();*/
