一、需求
- 给定一个二叉树
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 所示。序列化输出按层序遍历顺序(由 next 指针连接),'#' 表示每层的末尾。
提示:
- 树中的节点数小于
6000
-100 <= node.val <= 100
进阶:
- 你只能使用常量级额外空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
二、BFS
2.1 思路分析
- 题目要求将二叉树每一层的节点依次连接起来,最右侧的节点为null,这时候考虑使用二叉树的层序遍历,往往借助队列实现;
- 我们用队列存储每一层的节点,然后把这一层的节点取出来,取出来的过程中设置它们之间的next关系,关键要想明白如何在取出的过程中设置节点间的next关系;
- 这里需要联系到链表中的尾插法,即每次将取出的元素添加到链表的尾部,尾插法就需要尾指针始终指向链表的尾部元素;
2.2 代码实现
class Solution {
public Node connect(Node root) {
if(root == null) {
return null;
}
Queue<Node> queue = new LinkedList<>();
Node tail = null;
queue.add(root);
while(!queue.isEmpty()) {
int n = queue.size();
tail = null;
for(int i = 1; i <= n; i++) {
Node node = queue.poll();
if(node.left != null) {
queue.add(node.left);
}
if(node.right != null) {
queue.add(node.right);
}
//第一个节点直接作为tail
if(i == 1) {
tail = node;
} else {
tail.next = node;
tail = tail.next;
}
}
}
return root;
}
}
2.3 复杂度分析
- 时间复杂度为O(N),其中N为二叉树中的节点个数,每层建立链表需要遍历所有的节点;
- 空间复杂度为O(N),最坏情况下,当二叉树为满二叉树时,队列最多存储N/2个节点,即树的最后一层;
三、头节点dummy
3.1 思路分析
- 在遍历当前节点的时候,定义一个头节点dummy,它作为下一层"链表"的头节点,那么我们得构造出下一层的"链表",这时候我们利用的是链表中的尾插法,每次在链表的尾部添加一个元素;
- 当遍历完当前层的节点后,我们可以直接通过dummy跳转到下一层;
3.2 代码实现
class Solution {
public Node connect(Node root) {
Node cur = root;
//外循环的cur是每一层的起点
while(cur != null) {
Node dummy = new Node();
Node tail = dummy;
//这里是从每一层的起点开始,遍历当前层
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 = dummy.next;
}
}
}
3.3 复杂度分析
- 时间复杂度为O(N),其中N为二叉树的节点个数,需要遍历所有的二叉树节点;
- 空间复杂度为O(1),节点dummy和tail只占用常数级别的额外空间;
四、学习地址
作者:windliang