116.填充每个节点的下一个右侧节点指针
题目链接:力扣题目链接
难度:中等
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
二叉树定义如下
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 root;
}
//初始化一个队列,同时把第一层根节点存入队列中
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
//外层循环迭代的是层数
while(!queue.isEmpty()){
//记录当前队列大小
int len = queue.size();
//内部循环遍历这一层的所有节点
for(int i = 0;i<len;i++){
//从队首取出元素
Node tempNode = queue.poll();
//连接条件
if(i < len - 1){
tempNode.next = queue.peek();
}
if(tempNode.left != null){
queue.offer(tempNode.left);
}
if(tempNode.right !=null){
queue.offer(tempNode.right);
}
}
}
//返回根节点
return root;
}
}
方式二:递归代码
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;
}
}