题目描述:
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
来源:力扣(LeetCode)
思路:和116类似
116为完美二叉树!每个节点都有两个子节点,或者没有子节点!
1)使用队列,实现层序遍历连接,头节点的处理特殊
2)使用递归,将每一层连接成链表;题目给出的形式也是将每一层连接成了链表;同样116也可以做类似的实现;遍历上层链表,连接下层链表
使用了虚拟头节点,将头节点的处理常规化!
代码:
1)使用队列实现,简单!使用了额外空间
class Solution {
public Node connect(Node root) {
if(root == null) return root;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int size = queue.size();
Node node = queue.poll();
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
for(int i = 1;i < size;i++){
node.next = queue.peek();
node = queue.poll();
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
return root;
}
}
2)链表实现,省去了元素入队出队的开销
class Solution {
public Node connect(Node root) {
//依旧是层序遍历,但是不再要 队列这个辅助的遍历结构
if(root == null) return root;
Node cur = root;//一个临时节点改变链表的节点位置,保留root
cur.next = null;
while(cur != null){
//创建一个虚拟头节点,哨兵节点
Node temp = new Node(0);
Node pre = temp;
//遍历连接一层
while(cur != null){
if(cur.left != null){
pre.next = cur.left;
pre = pre.next;//前驱节点后移
}
if(cur.right != null){
pre.next = cur.right;
pre = pre.next;
}
cur = cur.next;
}
//往下一层移动
cur = temp.next;
}
return root;
}
}