Binary Search Tree Iterator LeetCode solution in JavaScript

1
/**
2
* Definition for a binary tree node.
3
* function TreeNode(val, left, right) {
4
* this.val = (val===undefined ? 0 : val)
5
* this.left = (left===undefined ? null : left)
6
* this.right = (right===undefined ? null : right)
7
* }
8
*/
9
/**
10
* @param {TreeNode} root
11
*/
12
var BSTIterator = function (root) {
13
this.stack = [];
14
this.node = root;
15
};
16

17
/**
18
* @return {number}
19
*/
20
BSTIterator.prototype.next = function () {
21
while (this.node) {
22
this.stack.push(this.node);
23
this.node = this.node.left;
24
}
25
const node = this.stack.pop();
26
this.node = node.right;
27
return node.val;
28
};
29

30
/**
31
* @return {boolean}
32
*/
33
BSTIterator.prototype.hasNext = function () {
34
return this.node || this.stack.length > 0;
35
};
36

37
/**
38
* Your BSTIterator object will be instantiated and called as such:
39
* var obj = new BSTIterator(root)
40
* var param_1 = obj.next()
41
* var param_2 = obj.hasNext()
42
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0