给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node
思路:
1.采用层次遍历:我们用队列queue来保存所有的结点,当队列不为空时进行操作(也就是遍历所有层),我们对同一层的结点进行遍历(以size为限制),除了最后一个结点,每个结点的next指针都指向下一个结点,为保证下一层的遍历,在对某个结点进行连接操作之后需要存储其孩子结点。
class Solution {
public Node connect(Node root) {
if(root==null){
return null;
}
Queue queue = new linkedList<>();
//根节点放入队列
queue.add(root);
//遍历层数
while(!queue.isEmpty()){
int size = queue.size();
//遍历该层结点,进行连接
for(int i=0;i
2.递归解法
每次递归,若当前结点的左右结点存在,就对当前结点的左右结点进行连接,如果当前结点有next结点,做特殊处理。这样一个结点就处理好了,再递归调用,对该结点的左右孩子结点进行同样的处理,最终得到结果。
class Solution {
public Node connect(Node root) {
if(root==null){
return null;
}
if(root.left!=null){
root.left.next = root.right;
if(root.next!=null){
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
}
return root;
}
}



