Skip to content

Commit 15fcce9

Browse files
committed
173. 二叉搜索树迭代器
1 parent cbc5cad commit 15fcce9

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@
7474
|151|[颠倒字符串中的单词](https://leetcode.cn/problems/reverse-words-in-a-string/)|[JavaScript](./algorithms/reverse-words-in-a-string.js)|Medium|
7575
|155|[最小栈](https://leetcode.cn/problems/min-stack/)|[JavaScript](./algorithms/min-stack.js)|Easy|
7676
|160|[相交链表](https://leetcode.cn/problems/intersection-of-two-linked-lists/)|[JavaScript](./algorithms/intersection-of-two-linked-lists.js)|Easy|
77+
|173|[二叉搜索树迭代器](https://leetcode.cn/problems/binary-search-tree-iterator/)|[JavaScript](./algorithms/binary-search-tree-iterator.js)|Medium|
7778
|189|[轮转数组](https://leetcode-cn.com/problems/rotate-array/)|[JavaScript](./algorithms/rotate-array.js)|Medium|
7879
|199|[二叉树的右视图](https://leetcode.cn/problems/binary-tree-right-side-view/)|[JavaScript](./algorithms/binary-tree-right-side-view.js)|Medium|
7980
|202|[快乐数](https://leetcode.cn/problems/happy-number/)|[JavaScript](./algorithms/happy-number.js)|Easy|
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
let prev = null;
14+
let head = null;
15+
// 中序遍历
16+
// 二叉搜索树 => 链表
17+
const toLinkedList = (root) => {
18+
if (!root) return null;
19+
toLinkedList(root.left);
20+
if (prev) {
21+
prev.right = root;
22+
} else {
23+
head = root;
24+
}
25+
root.left = null;
26+
prev = root;
27+
toLinkedList(root.right);
28+
};
29+
toLinkedList(root);
30+
this.head = head;
31+
const dummyNode = new TreeNode(-1);
32+
dummyNode.right = head;
33+
this.curr = dummyNode;
34+
};
35+
36+
/**
37+
* @return {number}
38+
*/
39+
BSTIterator.prototype.next = function () {
40+
this.curr = this.curr.right;
41+
return this.curr.val;
42+
};
43+
44+
/**
45+
* @return {boolean}
46+
*/
47+
BSTIterator.prototype.hasNext = function () {
48+
return !!this.curr.right;
49+
};
50+
51+
/**
52+
* Your BSTIterator object will be instantiated and called as such:
53+
* var obj = new BSTIterator(root)
54+
* var param_1 = obj.next()
55+
* var param_2 = obj.hasNext()
56+
*/

0 commit comments

Comments
 (0)