题目链接
思路:
对每一个节点来说,它的左孩子的next指针需要指向它的右孩子
如果当前节点的next指向不为空,则需要将它的右孩子的next指向它的next指向节点的左孩子
使用先序遍历处理整个流程
举例:
1
/ \
2 5
/ \ \
3 4 6
处理流程如下:
处理根节点 处理节点2 节点2next不为空 处理节点5
1 1 1 1
/ \ / \ / \ / \
2 -> 5 -> 2 -> 5 -> 2 -> 5 -> 2 -> 5
/ \ / \ / \ / \ / \ / \ / \ / \
3 4 6 7 3-> 4 6 7 3 -> 4-> 6 7 3-> 4-> 6 -> 7
代码如下:
public Node connect(Node root) {
if (root == null || root.left == null) {
return root;
}
root.left.next = root.right;
if (root.next != null) {
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
return root;
}
参考链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/comments/10182