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+ class BSTIterator {
17+ // First solution flatten the bst
18+ // List<Integer> list;
19+ // int index;
20+ Stack <TreeNode > stack ;
21+
22+ // public void inOrderTraversal(TreeNode root) {
23+ // if (root == null) {
24+ // return;
25+ // }
26+ // // Check left node
27+ // inOrderTraversal(root.left);
28+ // // Process this node
29+ // list.add(root.val);
30+ // // Check right node
31+ // inOrderTraversal(root.right);
32+ // }
33+
34+ public BSTIterator (TreeNode root ) {
35+ this .stack = new Stack <TreeNode >();
36+ // index = -1;
37+ // // Do the inOrderTraversal
38+ // inOrderTraversal(root);
39+ // Add all the leftmost elements to a stack so the smallest will be on top
40+ addLeftmost (root );
41+
42+ }
43+ public void addLeftmost (TreeNode node ) {
44+ while (node != null ) {
45+ stack .push (node );
46+ node = node .left ;
47+ }
48+ }
49+
50+ public int next () {
51+ // // Return the value at index + 1
52+ // if (hasNext()) {
53+ // index += 1;
54+ // return list.get(index);
55+ // } else {
56+ // return -1;
57+ // }
58+ TreeNode top = stack .pop ();
59+ if (top .right != null ) {
60+ // We have a right branch, add the leftmost element in this right branch
61+ // To maintain the smallest at top property
62+ addLeftmost (top .right );
63+ }
64+ return top .val ;
65+ }
66+
67+ public boolean hasNext () {
68+ return stack .size () > 0 ;
69+ }
70+ }
71+
72+ /**
73+ * Your BSTIterator object will be instantiated and called as such:
74+ * BSTIterator obj = new BSTIterator(root);
75+ * int param_1 = obj.next();
76+ * boolean param_2 = obj.hasNext();
77+ */
0 commit comments