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

使用指针连接二叉树所有兄弟节点的代码测试不通过,求问题排查

代码错误排查

核心问题分析

你的层序遍历思路本身是对的,问题出在dummy节点的创建时机和收尾逻辑,根据题目要求的两种常见场景,错误和修复方案如下:

场景1:要求所有节点按层序全局串联(前一层最后一个节点的next指向后一层第一个节点)

你在每一层遍历的时候都新建了dummy节点,直接导致层与层之间的连接断开。比如第一层遍历完根节点后,根节点的next还是默认值null,没有指向第二层的第一个节点。
修复代码:

public static void populate_sibling_pointers(BinaryTreeNode root) {
    if(root == null) return;
    Queue<BinaryTreeNode> q = new LinkedList<>();
    q.offer(root);
    // dummy节点移到循环外,全程复用记录上一个节点
    BinaryTreeNode dummy = new BinaryTreeNode(0);
    while(!q.isEmpty()){
        int size = q.size();
        for(int i = 0; i < size; i++){
            BinaryTreeNode cur = q.poll();
            dummy.next = cur;
            dummy = dummy.next;
            if(cur.left!=null){
                q.offer(cur.left);
            }
            if(cur.right!=null){
                q.offer(cur.right);
            }            
        }
    }
}

场景2:要求仅同层节点串联,每一层最后一个节点的next为null

你当前的代码已经实现了同层节点的串联,但如果节点初始化时next不是默认null,或者测试用例要求必须显式给每层最后一个节点的next赋值为null,只需要在每层遍历结束后补一个赋值操作即可。
修复代码:

public static void populate_sibling_pointers(BinaryTreeNode root) {
    if(root == null) return;
    Queue<BinaryTreeNode> q = new LinkedList<>();
    q.offer(root);

    while(!q.isEmpty()){
        int size = q.size();
        BinaryTreeNode dummy = new BinaryTreeNode(0);
        for(int i = 0; i < size; i++){
            BinaryTreeNode cur = q.poll();
            dummy.next = cur;
            dummy = dummy.next;
            if(cur.left!=null){
                q.offer(cur.left);
            }
            if(cur.right!=null){
                q.offer(cur.right);
            }            
        }
        // 显式将当前层最后一个节点的next设为null
        dummy.next = null;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:15:02