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

二叉树叶子节点同层校验代码无法通过所有测试用例排查求助

代码错误定位与修复

核心错误

Java 中基本数据类型是值传递,你代码里的ma是int基本类型,在solve方法内执行ma = h赋值时,仅修改了当前方法栈里的局部参数副本,所有其他递归分支拿到的ma永远是初始传入的-1。这就导致第一个叶子节点设置的深度不会同步给后续叶子节点做对比,不同深度的叶子节点永远不会触发h != ma的判断,逻辑直接失效。

次要问题

  • 缺少空树的边界处理,若传入的root为null,当前代码直接返回true,可根据题目要求调整逻辑
  • 原check方法末尾缺少闭合的大括号

修复方案

方案1:将ma改为类静态变量(和ans逻辑对齐)

static boolean ans;
static int ma; // 将ma提为静态变量,全局共享修改
static void solve(Node root,int h){
    if(root==null)
        return;
    if(!ans)
        return;
    if(root.left==null && root.right==null)
    {
        if(ma==-1)
            ma = h;
        else if(h != ma)
            ans = false;
        return;
    }
    solve(root.left,h+1);
    solve(root.right,h+1);
}
boolean check(Node root)
{
    ans = true;
    ma = -1;
    int h=0;
    solve(root,h);
    return ans;
}

方案2:用数组包装ma(避免静态变量,多线程场景更安全)

static void solve(Node root,int h,int[] ma, boolean[] ans){
    if(root==null)
        return;
    if(!ans[0])
        return;
    if(root.left==null && root.right==null)
    {
        if(ma[0]==-1)
            ma[0] = h;
        else if(h != ma[0])
            ans[0] = false;
        return;
    }
    solve(root.left,h+1,ma,ans);
    solve(root.right,h+1,ma,ans);
}
boolean check(Node root)
{
    boolean[] ans = {true};
    int[] ma = {-1};
    int h=0;
    solve(root,h,ma,ans);
    return ans[0];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 10:15:04