一、需求
- 给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node { int val; Node *left; Node *right; Node *next; }
- 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为
NULL
; - 初始状态下,所有 next 指针都被设置为
NULL
;
输入:root = [1,2,3,4,5,6,7]
输出:[1,#,2,3,#,4,5,6,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由 next 指针连接,'#' 标志着每一层的结束。
提示:
- 树中节点的数量少于
4096
-1000 <= node.val <= 1000
进阶:
- 你只能使用常量级额外空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度
二、递归法
2.1 思路分析
- 现在要想办法将完美二叉树每一层的节点连接起来,定义一个方法,先将当前层的左右子树根节点连接起来,然后递归连接左子树,递归连接右子树,最后还要连接左子树的右孩子和右子树的左孩子;
- 因为这是一棵完美二叉树,左右子树节点要么同时为null,要么同时不为null;
2.2 代码实现
class Solution {
public Node connect(Node root) {
if(root == null) {
return null;
}
root.next = null;
connectLeftAndRight(root.left, root.right);
return root;
}
//该方法将每一层二叉树的节点连接起来
private void connectLeftAndRight(Node leftNode, Node rightNode) {
//这是完美二叉树,左右节点同时为null或不为null
if(leftNode == null && rightNode == null) {
return;
}
leftNode.next = rightNode;
//完成左子树右连接
connectLeftAndRight(leftNode.left, leftNode.right);
//完成右子树右连接
connectLeftAndRight(rightNode.left, rightNode.right);
//将左右子树连接
connectLeftAndRight(leftNode.right, rightNode.left);
}
}
2.3 复杂度分析
- 时间复杂度为O(N);
- 空间复杂度为O(1),题目规定递归不占用额外空间;
三、BFS
3.1 思路分析
- 这里的思路与填充每个节点的下一个右侧节点指针:https://blog.csdn.net/Sruggle/article/details/115174627中解法一完全相同;
3.2 代码实现
class Solution {
public Node connect(Node root) {
if(root == null) {
return root;
}
Deque<Node> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
int n = queue.size();
Node 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);
}
//关键在于建立链表这部分
if(i == 1) {
tail = node;
} else {
tail.next = node;
tail = tail.next;
}
}
}
return root;
}
}
3.3 复杂度分析
- 时间复杂度为O(N),其中N为二叉树的节点个数;
- 空间复杂度为O(N),队列最多同时存储N/2个节点;
四、头节点dummy
4.1 思路分析
- 这里的思路与填充每个节点的下一个右侧节点指针:https://blog.csdn.net/Sruggle/article/details/115174627中解法二完全相同;
4.2 代码实现
class Solution {
public Node connect(Node root) {
Node cur = root;
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;
}
return root;
}
}
4.3 复杂度分析
- 时间复杂度为O(N);
- 空间复杂度为O(1);