题目的链接在这里:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/
题目大意
给定一个二叉树struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
一、示意图
二、解题思路
BFS
BFS
代码如下:
/*
// 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) {
//填充他的右侧next节点 找不到就是null BFS即可
Queue<Node> queue=new LinkedList<>();
if(root==null){
return root;
}
if(root.left==null&&root.right==null){
root.next=null;
return root;
}
//然后开始
queue.add(root);
while (!queue.isEmpty()){
int size=queue.size();
//然后开始判断
for(int i=0;i<size;i++){
Node poll = queue.poll();
if(poll.left!=null){
queue.add(poll.left);
}
if(poll.right!=null){
queue.add(poll.right);
}
//然后是他自己
if(i==size-1){
//说明是最后一个
poll.next=null;
}
else{
poll.next=queue.peek();
}
}
}
return root;
}
}