You need to enable JavaScript to run this app. Java递归实现二叉树所有节点深度和多测试用例失败问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Java递归实现二叉树所有节点深度和多测试用例失败问题排查

问题根因

完全是你代码里的static变量finalSum导致的,算法逻辑本身没有问题。

  • static变量属于类级别,不属于单次方法调用的临时变量,只要JVM进程不重启、类不被重新加载,这个变量会一直保留上一次执行后的残留值。
  • AlgoExpert的测试运行机制是在同一个JVM进程内连续跑所有测试用例,每次跑测试前不会重置你定义的类的静态变量。第一次测试跑完finalSum存了16,第二次调用nodeDepths的时候没有把它重置为0,直接在16的基础上累加新的计算结果,所以你看到的所有后续输出都是之前所有测试结果的累加和。
  • 你之前在LeetCode上没遇到这个问题,是因为LeetCode的测试运行器每个测试用例执行前,会重新编译、加载你的代码,静态变量会被重置为初始值,自然不会出现累加的问题。
现有逻辑校验

你当前的递归计算逻辑是正确的:根节点深度为0不需要计入总和,从左右子节点开始初始runningSum为0,每下一层加1,每到一个节点就把当前深度加到总和里,对示例树的计算结果确实为16,没有逻辑错误。
但这种依赖静态变量的写法本身就存在跨用例污染的隐患。

修正方案

最稳妥的写法是不要使用类级别的静态变量,把累加逻辑通过递归返回值传递,每次调用方法的时候不会残留之前的状态:

import java.util.*;

class Program {

  public static int nodeDepths(BinaryTree root) {
    return depthHelper(root, -1);
  }
    
  private static int depthHelper(BinaryTree node, int currentDepth) {
    if(node == null) return 0;
    int depth = currentDepth + 1;
    return depth + depthHelper(node.left, depth) + depthHelper(node.right, depth);
  }

  static class BinaryTree {
    int value;
    BinaryTree left;
    BinaryTree right;

    public BinaryTree(int value) {
      this.value = value;
      left = null;
      right = null;
    }
  }
}

如果要保留你之前的写法,只需要在nodeDepths方法的第一行把finalSum重置为0也能通过测试,但这种写法不推荐:

public static int nodeDepths(BinaryTree root) {
    finalSum = 0; // 每次调用先清空残留值
    int runningSum = 0;
    depthHelper(root.left, runningSum);
    depthHelper(root.right, runningSum);
    return finalSum;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.26 08:15:08