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

问题

分析

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
class Solution {
public Node connect(Node root) {
if (root == null) {
return null;
}
Node res = root;
// 外层循环为树高的迭代
while (root != null) {
Node nextLayerHead = new Node(0);
Node nextLayerNode = nextLayerHead;
// 内层循环根据当前层已有的链表构建下一层的链表
while (root != null) {
if (root.left != null) {
nextLayerNode.next = root.left;
nextLayerNode = nextLayerNode.next;
}
if (root.right != null) {
nextLayerNode.next = root.right;
nextLayerNode = nextLayerNode.next;
}
root = root.next;
}
root = nextLayerHead.next;
}
return res;
}
}