Binary Search Tree Iterator LeetCode solution in Java

1
class BSTIterator {
2

3
TreeNode root;
4
TreeNode current;
5
Stack<TreeNode> st = new Stack<>();
6

7
public BSTIterator(TreeNode root) {
8
this.root = root;
9
// init(root);
10
current = findLeft(root);
11
// System.out.println("Init: stack is: "+st);
12
}
13

14
public int next() {
15

16
int val = -1;
17
if (current != null) val = current.val;
18
else return -1;
19

20
if (current.right != null) current = findLeft(current.right);
21
else if (!st.isEmpty()) current = st.pop();
22
else current = null;
23
// System.out.println("next: stack is: "+st);
24
return val;
25
}
26

27
public TreeNode findLeft(TreeNode node) {
28

29
if (node == null) return null;
30

31
if (node.left != null) {
32
TreeNode next = node.left;
33
st.push(node);
34
return findLeft(next);
35
} else return node;
36
}
37

38
public boolean hasNext() {
39
return current != null;
40
}
41
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0