题目链接
思路:
解法一:
使用层次遍历来进行求解,当遍历到每一层时,这一层中的节点(除了最后一个节点)的next指针均指向同一层中的下一个节点,也就是next指向队列中的下一个元素。
public Node connect(Node root) {
if (root == null) {
return root;
}
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
// 当前层的节点数
int size = queue.size();
for (int i = 0; i < size; i++) {
Node tmp = queue.poll();
// i < size-1 时,说明不是这一层的最后一个节点
if (i < size - 1) {
tmp.next = queue.peek();
}
if (tmp.left != null) {
queue.add(tmp.left);
}
if (tmp.right != null) {
queue.add(tmp.right);
}
}
}
return root;
}
解法二:
直接使用递归进行求解。
对于每一个节点来说,
(1)它的左孩子右孩子都存在的情况下,它的左孩子的next指针应指向其右孩子
1 1
/ \ -> / \
2 3 2 -> 3
(2)它的右孩子不存在时,它的左孩子的next指针应指向它的next指针的孩子
... ...
/ \ / \
1 -> 4 -> 1 -> 4
/ / \ / / \
2 5 6 2 ---> 5 6
(3)它的左孩子不存在时,它的右孩子的next指针应指向它的next指针的孩子,跟(2)同样
public Node connect(Node root) {
if (root == null) {
return root;
}
// 左孩子右孩子都不为空,则左孩子next指向右孩子
if (root.left != null && root.right != null) {
root.left.next = root.right;
}
// 左孩子不空,右孩子为空,那么左孩子的next应指向当前节点的next节点的孩子
if (root.left != null && root.right == null) {
root.left.next = getNext(root.next);
}
// 左孩子为空,右孩子的next应指向当前节点的next节点的孩子
if (root.right != null) {
root.right.next = getNext(root.next);
}
// 此处格外注意,应先对右子树进行遍历,防止出现信息链缺失问题
// 可以自己试一下先左子树,会发现问题
connect(root.right);
connect(root.left);
return root;
}
private Node getNext(Node root) {
while (root != null) {
if (root.left != null) {
return root.left;
}
if (root.right != null) {
return root.right;
}
root = root.next;
}
return root;
}
代码参考自:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/comments/45416