解法一:前序遍历递归

在构造函数中进行前序遍历递归,获取完整的二叉搜索树节点序列。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class BSTIterator {
  11. List<Integer> list;
  12. int index = 0;
  13. public BSTIterator(TreeNode root) {
  14. list = new LinkedList<>();
  15. preOrder(root);
  16. }
  17. private void preOrder(TreeNode root) {
  18. if (root == null) {
  19. return;
  20. }
  21. if (root.left != null) {
  22. preOrder(root.left);
  23. }
  24. list.add(root.val);
  25. if (root.right != null) {
  26. preOrder(root.right);
  27. }
  28. }
  29. /**
  30. * @return the next smallest number
  31. */
  32. public int next() {
  33. return list.get(index++);
  34. }
  35. /**
  36. * @return whether we have a next smallest number
  37. */
  38. public boolean hasNext() {
  39. return index < list.size();
  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. */

解法二:用栈模拟递归

用栈模拟递归的过程,这样可以自己控制遍历的开始和终止。
参考官方题解:https://leetcode-cn.com/problems/binary-search-tree-iterator/solution/er-cha-sou-suo-shu-die-dai-qi-by-leetcode/

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class BSTIterator {
  11. Deque<TreeNode> stack;
  12. public BSTIterator(TreeNode root) {
  13. stack = new LinkedList<>();
  14. leftOrder(root);
  15. }
  16. private void leftOrder(TreeNode root) {
  17. if (root == null) {
  18. return;
  19. }
  20. stack.push(root);
  21. if (root.left != null) {
  22. leftOrder(root.left);
  23. }
  24. }
  25. /**
  26. * @return the next smallest number
  27. */
  28. public int next() {
  29. TreeNode nextNode = stack.pop();
  30. if (nextNode.right != null) {
  31. leftOrder(nextNode.right);
  32. }
  33. return nextNode.val;
  34. }
  35. /**
  36. * @return whether we have a next smallest number
  37. */
  38. public boolean hasNext() {
  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. */