给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public Node connect(Node root) {
if(root==null){
return null;
}
help(root);
return root;
}
private void help(Node root){
if(root.right==null&&root.left==null){
return;
}
root.left.next =root.right;
if(root.next!=null){
root.right.next=root.next.left;
}
help(root.left);
help(root.right);
}
}
在递归函数help中,我们判断到叶子节点时返回,由于给定树为完美二叉树,则我们先将本节点的左孩子next指针指向本节点的右孩子, 其次,我们判断本节点的next是否存在,如果存在,则将右孩子节点的next指向本节点next的左孩子,递归调用即可