117. 填充每个节点的下一个右侧节点指针 II
题目
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
进阶:
- 你只能使用常量级额外空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
分析
首先看到这道题,想到BFS,但是需要空间复杂度为O(n)。这时考虑到上一层的节点BFS的顺序中优先通过next连在一起了,也就是说只要知道上一层最开始的节点first_node,就可以知道上面一层。所以一共需要初始化三个节点node–上一层遍历节点,cur_node–当前层遍历节点以及first_node–存储当前层第一个节点。注意每层结束后需要将first_node复制为node,相当于跳往下一层。并将first_node清空。
需要两次for循环,外面的遍历来遍历每一层,里面的遍历来遍历上一层node。
代码
public Node connect(Node root) {
Node node = root;
Node first_node = null;
Node cur_node = null;
while(node!=null){
while(node!=null){
if(node.left!=null){
if(first_node==null){
first_node = node.left;
cur_node = node.left;
}
else {
cur_node.next = node.left;
cur_node = cur_node.next;
}
}
if(node.right!=null){
if(first_node==null){
first_node = node.right;
cur_node = node.right;
}
else {
cur_node.next = node.right;
cur_node = cur_node.next;
}
}
node = node.next;
}
node = first_node;
first_node = null;
}
return root;
}
结果
时间超过100%
内存超过22.59%