You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode填充每个节点的下一个右侧节点指针:队列为何存在null?

问题排查:为何curr会出现null值

你的代码里curr出现null的核心原因如下:

  • 初始入队的root可能为null:当输入的是空树(root=null)时,你直接执行q.add(root),会把null元素加入队列。第一次进入内层循环时,取出的curr就是null,若没有if(curr==null) break;,会直接触发空指针异常。
  • 题目明确是完美二叉树(每个非叶子节点都有左右子节点),所以只要当前节点curr不为null,它的left和right一定不为null,因此childQ中不会被加入null元素。队列中出现null的唯一入口就是初始时的q.add(root)。

你的临时判断if(curr==null) break;能通过测试,是因为它刚好处理了root=null的边界情况,但本质是队列中不该出现null元素,这个判断属于临时补丁。

修正后的严谨写法

可以在初始入队前就判断root是否为null,从根源避免队列中出现null元素,同时优化层遍历逻辑:

class Solution {
    public Node connect(Node root) {
        if (root == null) return null;
        Queue<Node> q = new LinkedList<>();
        q.add(root);
        
        while(!q.isEmpty())
        {
            Queue<Node> childQ = new LinkedList<>();
            int levelSize = q.size();
            for (int i = 0; i < levelSize; i++) {
                Node curr = q.remove();
                // 当前层最后一个节点的next设为null,否则指向队列中下一个节点
                curr.next = i == levelSize - 1 ? null : q.peek();
                childQ.add(curr.left);
                childQ.add(curr.right);
            }
            q = childQ;
        }
        return root;
    }
}

内容的提问来源于stack exchange,提问作者Iggee Xy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:22:19