力扣面试150 填充每个节点的下一个右侧节点指针 II BFS 逐层构建法

Problem: 117. 填充每个节点的下一个右侧节点指针 II

🍻 BFS 空间优化

👩‍🏫 参考题解

  • ⏰ 时间复杂度: O ( n ) O(n) O(n)
  • 🌎 空间复杂度: O ( 1 ) O(1) O(1)
Java 复制代码
class Solution {
    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        Node ans = root;
        Node cur = root;// 上一层链表的头结点
        while(cur != null){
            Node head = new Node(-1), tail = head;// 当前层的头尾结点
            for(Node i = cur; i != null; i = i.next){ // 遍历上一层链表的每个节点的左右孩子
                if(i.left != null){// 先加左孩子到当前层的链表
                    tail.next = i.left;
                    tail = tail.next;
                }
                if(i.right != null){// 再加右孩子到当前层的链表
                    tail.next = i.right;
                    tail = tail.next;
                }
            }
            cur = head.next;// 移动到下一层
        }
        
        return ans;
    }
}
相关推荐
无敌昊哥战神4 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
x_xbx5 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
木井巳7 小时前
【递归算法】子集
java·算法·leetcode·决策树·深度优先
lightqjx7 小时前
【算法】二分算法
c++·算法·leetcode·二分算法·二分模板
发现一只大呆瓜8 小时前
深入浅出 AST:解密 Vite、Babel编译的底层“黑盒”
前端·面试·vite
灰色小旋风8 小时前
力扣21 合并两个有序链表(C++)
c++·leetcode·链表
发现一只大呆瓜8 小时前
前端模块化:CommonJS、AMD、ES Module三大规范全解析
前端·面试·vite
用户851160276129 小时前
Spring Boot 自动配置原理是什么?
面试
kyriewen9 小时前
异步编程:从“回调地狱”到“async/await”的救赎之路
前端·javascript·面试
秋水无痕10 小时前
# 手把手教你从零搭建 AI 对话系统 - React + Spring Boot 实战(二)
前端·后端·面试