-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-search-tree-iterator.js
More file actions
65 lines (61 loc) · 1.46 KB
/
binary-search-tree-iterator.js
File metadata and controls
65 lines (61 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
*/
var BSTIterator = function(root) {
this.arr = [];
traverse(root, this.arr);
function traverse(root, arr){ //TreeNode root, Target arr.
// Stop case when both left:null && right:null;
if (root === null) {
return arr;
}
// traverse/ travel across left root if not null
arr = traverse(root.left, arr);
// Smallest number left to right.
arr.push(root.val);
// traverse/ travel across right root if not null
arr = traverse(root.right, arr);
return arr;
}
};
/**
* @return the next smallest number
* @return {number}
*/
BSTIterator.prototype.next = function() {
/*
[ 3, 7, 9, 15, 20 ]
[ 7, 9, 15, 20 ]
[ 9, 15, 20 ]
[ 15, 20 ]
[ 20 ]
*/
return this.arr.shift();
};
/**
* @return whether we have a next smallest number
* @return {boolean}
*/
BSTIterator.prototype.hasNext = function() {
/*
[ 9, 15, 20 ]
[ 15, 20 ]
[ 20 ]
[]
*/
return this.arr.length > 0;
};
/**
* Your BSTIterator object will be instantiated and called as such:
* var obj = new BSTIterator(root)
* var param_1 = obj.next()
* var param_2 = obj.hasNext()
*/