【题目】*117. 填充每个节点的下一个右侧节点指针 II & *116. 填充每个节点的下一个右侧节点指针
这两题的区别是,116题是完全二叉树,117题是普通二叉树,下面以普通二叉树作答
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
进阶:
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
示例:
输入:root = [1,2,3,4,5,null,7]
输出:[1,#,2,3,#,4,5,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
提示:
树中的节点数小于 6000
-100 <= node.val <= 100
【解题思路1】BFS
从右到左BFS遍历,借助队列
class Solution {
public Node connect(Node root) {
if(root == null) return null;
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
int size = queue.size();
Node pre = null;
for(int i = 0; i < size; i++) {
Node temp = queue.poll();
temp.next = pre;
pre = temp;
if(temp.right != null) queue.offer(temp.right);
if(temp.left != null) queue.offer(temp.left);
}
}
return root;
}
}
改进:无需借助队列
已经填充好的每一层结点,其实已经组成了一个单向的链表,只要获取下一层链表的头结点,即可遍历下一层所有结点,所以只需要使用一个变量指向头节点。
public class Solution {
public Node connect(Node root) {
Node cur = root;
while (cur != null) {
//head.next指向下一层层头
Node head = new Node(0);
Node temp = head;
//遍历当前层所有结点,并将下一层结点串成一个单链表
while (cur != null) {
if (cur.left != null) {
temp.next = cur.left;
temp = temp.next;
}
if (cur.right != null) {
temp.next = cur.right;
temp = temp.next;
}
//访问本层下一个结点
cur = cur.next;
}
//指向下一层头结点
cur = head.next;
}
return root;
}
}