Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c25dfdb

Browse files
Binary Search Tree Iterator
1 parent 806cc98 commit c25dfdb

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎0173_binarySearchTreeIterator.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* @typedef {Object} TreeNode
3+
* @description Definition for a binary tree node.
4+
* @example
5+
* function TreeNode(val, left, right) {
6+
* this.val = (val===undefined ? 0 : val)
7+
* this.left = (left===undefined ? null : left)
8+
* this.right = (right===undefined ? null : right)
9+
* }
10+
*/
11+
12+
/**
13+
* Iterator over a binary search tree
14+
* @summary Binary Search Tree Iterator {@link https://leetcode.com/problems/binary-search-tree-iterator/}
15+
* @description Given a root node of BST, implement an iterator that returns smallest available number.
16+
*/
17+
class BSTIterator {
18+
constructor(root) {
19+
this.node = root;
20+
this.stack = [];
21+
}
22+
23+
/**
24+
* Space O(1) , Time O(1)
25+
*/
26+
hasNext() {
27+
return this.node || this.stack.length;
28+
}
29+
30+
/**
31+
* Space O(n) - worst case stack will have all nodes.
32+
* Time O(n) - worst case iterate over all nodes.
33+
*/
34+
next() {
35+
while (this.node) {
36+
this.stack.push(this.node);
37+
this.node = this.node.left;
38+
}
39+
40+
this.node = this.stack.pop();
41+
const result = this.node.val;
42+
this.node = this.node.right;
43+
44+
return result;
45+
}
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /