题目
思路
本题可采用层序遍历法
层序遍历法除了要返回的list之外还要借助queue这个数据结构
如果根节点为空,则直接返回
当节点不为空时,将其加入到队列中,当队列不为空的时候,开始遍历
先定义一个整数len用来表示队列的长度que.size(),当len-->0时,从队列中取出一个节点,如果len不等于0(poll出来的节点不是本层最后一个),使节点指向本层下一个节点(下一个节点已在队列中,所以peek一下就ok),然后再把节点的左右子节点加入到que中
循环遍历每一层给,返回root
代码
class Solution {
public Node connect(Node root) {
if(root==null){
return root;
}
Queue<Node> que = new LinkedList<>();
que.offer(root);
while(!que.isEmpty()){
int len = que.size();
while(len-->0){
Node node =que.poll();
if(len!=0){
node.next=que.peek();
}
if(node.left!=null){
que.offer(node.left);
}
if(node.right!=null){
que.offer(node.right);
}
}
}
return root;
}
}
收获
node指向下一个节点应该写为node.next=xxx