binary search tree iterator ii leetcode

Solutions on MaxInterview for binary search tree iterator ii leetcode by the best coders in the world

showing results for - "binary search tree iterator ii leetcode"
Enrico
06 Aug 2016
1class BSTIterator {
2
3    List<Integer> arr = new ArrayList();
4    int pointer;
5    int n;
6    
7    public void inorder(TreeNode r, List<Integer> arr) {
8        if (r == null) return;
9        inorder(r.left, arr);
10        arr.add(r.val);
11        inorder(r.right, arr);
12    }
13
14    public BSTIterator(TreeNode root) {
15        inorder(root, arr);
16        n = arr.size();
17        pointer = -1;
18    }
19    
20    public boolean hasNext() {
21        return pointer < n - 1;
22    }
23    
24    public int next() {
25        ++pointer;
26        return arr.get(pointer);
27    }
28    
29    public boolean hasPrev() {
30        return pointer > 0;
31    }
32    
33    public int prev() {
34        --pointer;
35        return arr.get(pointer);
36    }
37}