给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
思路
(1)借用了之前的LeetCode-Tree-102-M:二叉树的层次遍历的两个队列的思想,但是不够优化。
(2)优化,借助size
变量去掉一个队列。
(3)递归,常数级的空间复杂度。
解法1-两个队列
执行用时 :6 ms, 在所有 Java 提交中击败了5.57%的用户
内存消耗 :38.6 MB, 在所有 Java 提交中击败了44.20%的用户
class Solution {
Queue<Node> queue1 = new LinkedList<>();
Queue<Node> queue2 = new LinkedList<>();
public Node connect(Node root) {
// 层序遍历
if(root == null){
return null;
}
Node head = root;
queue2.offer(root);
while(!queue1.isEmpty() || !queue2.isEmpty()){
while(queue1.isEmpty()){
queue1 = new LinkedList<>(queue2);
queue2.clear();
}
Node curNode=null;
if(queue1.size()>1){
curNode = queue1.poll();
curNode.next = queue1.peek();
}else{
curNode = queue1.poll();
curNode.next = null;
}
if(curNode.left != null){
queue2.add(curNode.left);
}
if(curNode.right != null){
queue2.add(curNode.right);
}
}
return head;
}
}
解法2-一个队列的BFS
(1)使用size变量解决了树的程序遍历中涉及的痛点问题。
空间复杂度:O(n)
执行用时 :3 ms, 在所有 Java 提交中击败了20.42%的用户
内存消耗 :39.9 MB, 在所有 Java 提交中击败了5.00%的用户
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();
for(int i=0; i<size; i++){
Node cur =queue.poll();
if( i+1 ==size){
cur.next = null;
}else{
cur.next = queue.peek();
}
if(cur.left != null){
queue.offer(cur.left);
}
if(cur.right != null){
queue.offer(cur.right);
}
}
}
return root;
}
}
解法3-递归
执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :39.6 MB, 在所有 Java 提交中击败了12.30%的用户
class Solution {
public Node connect(Node root) {
if(root == null){
return null;
}
if(root.left != null){
root.left.next = root.right;
if(root.next != null){
root.right.next = root.next.left;
}
}
connect(root.left);
connect(root.right);
return root;
}
}