力扣面试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;
    }
}
相关推荐
Miraitowa_cheems10 分钟前
LeetCode算法日记 - Day 104: 通配符匹配
linux·数据结构·算法·leetcode·深度优先·动态规划
Chan1623 分钟前
【 Java八股文面试 | Redis篇 缓存问题、持久化、分布式锁 】
java·数据库·redis·后端·spring·缓存·面试
zhishidi2 小时前
大模型个性化推荐面试指南
人工智能·面试
不穿格子的程序员3 小时前
从零开始写算法——二分-搜索二维矩阵
线性代数·算法·leetcode·矩阵·二分查找
Kuo-Teng3 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
Kuo-Teng4 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
元亓亓亓5 小时前
LeetCode热题100--39. 组合总和
算法·leetcode·职场和发展
2401_841495646 小时前
【LeetCode刷题】找到字符串中所有字母异位词
数据结构·python·算法·leetcode·数组·滑动窗口·找到字符串中所有字母异位词
橘颂TA6 小时前
【剑斩OFFER】算法的暴力美学——寻找数组的中心下标
算法·leetcode·职场和发展·结构与算法
py有趣6 小时前
LeetCode算法学习之鸡蛋掉落
学习·算法·leetcode