173. 二叉搜索树迭代器

实现一个二叉搜索树迭代器类BSTIterator ,表示一个按中序遍历二叉搜索树(BST)的迭代器:

  • BSTIterator(TreeNode root) 初始化 BSTIterator 类的一个对象。BST 的根节点 root 会作为构造函数的一部分给出。指针应初始化为一个不存在于 BST 中的数字,且该数字小于 BST 中的任何元素。

  • boolean hasNext() 如果向指针右侧遍历存在数字,则返回 true ;否则返回 false 。

  • int next()将指针向右移动,然后返回指针处的数字。

注意,指针初始化为一个不存在于 BST 中的数字,所以对 next() 的首次调用将返回 BST 中的最小元素。

你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 的中序遍历中至少存在一个下一个数字。

链接

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
66
67
/**
* 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.first = null
this.end = false
this.initData(root)
};

BSTIterator.prototype.initData = function(root) {
if (root === null) return
root.right && (root.right.parent = root)
this.initData(root.right)
root.left && (root.left.parent = root)
this.first = root
this.initData(root.left)
};

/**
* @return {number}
*/
BSTIterator.prototype.next = function() {
let res = this.first
this.first.isReaded = true
if (this.first.right) {
let right = this.first.right
while(right) {
this.first = right
right = right.left
}
} else {
let parent = this.first.parent
if (parent && !this.end) {
while(parent.parent && parent.isReaded) {
parent = parent.parent
}
if (parent.isReaded) {
this.end = true
} else {
this.first = parent
}
}
}
return res.val
};

/**
* @return {boolean}
*/
BSTIterator.prototype.hasNext = function() {
return !this.first.isReaded
};

/**
* 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()
*/

栈堆解法

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
/**
* 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.stack = []
this.cur = root
};


/**
* @return {number}
*/
BSTIterator.prototype.next = function() {
while(this.cur) {
this.stack.push(this.cur)
this.cur = this.cur.left
}
this.cur = this.stack.pop()
const ret = this.cur.val
this.cur = this.cur.right
return ret
};

/**
* @return {boolean}
*/
BSTIterator.prototype.hasNext = function() {
return this.cur !== null || this.stack.length
};

/**
* 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()
*/