填充每个节点的下一个右侧节点指针

使用队列

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
/**
* // Definition for a _Node.
* function _Node(val, left, right, next) {
* this.val = val === undefined ? null : val;
* this.left = left === undefined ? null : left;
* this.right = right === undefined ? null : right;
* this.next = next === undefined ? null : next;
* };
*/

/**
* @param {_Node} root
* @return {_Node}
*/
var connect = function (root) {
if (!root) return null;
// 层序遍历
// 完美二叉树
let queue = [root];
let cur = root;
while (queue.length) {
const newQueue = [];
let prevNode = null;
while (queue.length) {
const node = queue.pop();
if (prevNode) {
prevNode.next = node;
}
prevNode = node;
if (node.left) {
newQueue.unshift(node.left);
}
if (node.right) {
newQueue.unshift(node.right);
}
}
if (newQueue.length) {
queue = newQueue;
}
}
return root;
};

层序遍历,空间复杂度O(1)

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
/**
* // Definition for a _Node.
* function _Node(val, left, right, next) {
* this.val = val === undefined ? null : val;
* this.left = left === undefined ? null : left;
* this.right = right === undefined ? null : right;
* this.next = next === undefined ? null : next;
* };
*/

/**
* @param {_Node} root
* @return {_Node}
*/
var connect = function (root) {
// 如果为空的话就返回null
if (!root) return null;
let leftMost = root;
while (leftMost.left) {
let head = leftMost;
while (head) {
// head.left一定存在,head.right也存在,因为是完美二叉树
// 连接左右
head.left.next = head.right;
if (head.next) {
head.right.next = head.next.left;
}
head = head.next;
}
leftMost = leftMost.left;
}
return root;
};

本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。