给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
提示:
- 你只能使用常量级额外空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
解法一
迭代
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if (root == null) return null;
//迭代
Node pre = root;
//遍历每一层(因为是完美二叉树,所以判断左节点即可)
while (pre.left != null) {
Node temp = pre;
//遍历当前层
while (temp != null) {
//连接左节点
temp.left.next = temp.right;
//连接右节点
if (temp.next != null) {
temp.right.next = temp.next.left;
}
//往next继续走,直到temp为空
temp = temp.next;
}
//当前层走完,进入下一层
pre = pre.left;
}
return root;
}
这道题第一反应是用队列,BFS来着,不过看到下面提示说只能使用常量级额外空间,就没思路了,果然还是题做少了,看了题解区后,发现自己进入了误区,我想的是当前节点怎么连到右边的节点,看了题解后发现可以在父节点就把中间节点连接起来,思路来着王尼玛
大佬的题解,写得很详细,powcai
大佬的做法有些许不同,meifans
大佬的题解最秀(解法三),应该是最完美的答案了。
解法二
递归
class Solution {
public Node connect(Node root) {
//递归
if (root == null || root.left == null) return root;
//循环,把中间部分连接上
root.left.next = root.right;
//通过当前节点,连接right节点,一直循环到叶子节点
Node temp = root.left;
while (temp.right != null) {
temp.right.next = temp.next.left;
temp = temp.right;
}
//递归
connect(root.left);
connect(root.right);
return root;
}
}
解法三
递归
class Solution {
public Node connect(Node root) {
//递归2
dfs(root, null);
return root;
}
private void dfs(Node node, Node next) {
if (node != null) {
//当前节点连接上传递过来的next节点
node.next = next;
//连接左右节点
dfs(node.left, node.right);
//连接右节点(如果当前节点的next不为空,节点next节点的left节点,否则连接null)
dfs(node.right, node.next != null ? node.next.left : null);
}
}
}