力扣面试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;
    }
}
相关推荐
文丑颜不良啊7 小时前
LeetCode2821~2840题目解析
java·leetcode
Pniubi11 小时前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表
nice_lcj52011 小时前
LRU 缓存入门:它是什么、怎么用、面试怎么手写
java·数据结构·缓存·面试·lru
文丑颜不良啊12 小时前
LeetCode2741~2760题目解析
java·leetcode
俊俊几年的12 小时前
动态规划(Dynamic Programming)详解:从入门到 LeetCode Hot 100
linux·c++·算法·leetcode·嵌入式·动态规划·c
聪明的笨猪猪1 天前
企业知识库AI架构选型:落地导向的架构决策与组件清单
经验分享·面试·架构·embedding·数据库架构
希望我万事顺遂1 天前
力扣hot100-滑动窗口最大值
数据结构·算法·leetcode
是main不是漫2 天前
【双指针|LeetCode1089 复写零】巧用逆向思路,破解原地覆盖陷阱
数据结构·算法·leetcode
stormzhangV2 天前
涨薪 50% 怎么做到的?
人工智能·面试·aigc