给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。

分析:这题 首先注意一点,每个节点 next 最初都是null,输出就是#
解法一:
BFS 老层次遍历了
/**
BFS
**/
public Node connect(Node root) {
if(root == null){
return null;
}
Queue<Node> path = new LinkedList<>();
path.offer(root);
while(!path.isEmpty()){
Node last = null;
int n = path.size();
for (int i = 1 ; i<= n ; i++){
Node temp = path.poll();
if(temp.left!=null){
path.offer(temp.left);
}
if(temp.right!= null){
path.offer(temp.right);
}
if (i != 1) {
last.next = temp;
}
last = temp;
}
}
return root;
}
方法二:BFS(进阶,节省了空间,因为 树结构已经固定 只能从空间上优化)
public Node connect(Node root) {
Node cur = root;
while (cur != null) {
Node dummy = new Node();
Node tail = dummy;
//遍历 cur 的当前层
while (cur != null) {
if (cur.left != null) {
tail.next = cur.left;
tail = tail.next;
}
if (cur.right != null) {
tail.next = cur.right;
tail = tail.next;
}
cur = cur.next;
}
//更新 cur 到下一层
cur = dummy.next;
}
return root;
}