题目描述
给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
来源:力扣
解题思路
运用递归,如果左右节点存在,将左节点的next指向右节点。难点在于将右节点连接到对应的左节点上,如果根节点的next已经连接完毕,那么就很容易找到对应的左节点了。
代码
class Solution {
public Node connect(Node root) {
if(root==null) return null;
if(root.left!=null && root.right!=null){ root.left.next = root.right;
if(root.next!=null) root.right.next = root.next.left;
}
if(root.left != null) connect(root.left);
if(root.right != null) connect(root.right);
return root;
}
}