我不知道为什么以及如何在迭代期间将maxsum重置为0。
在计算叶的最大和时,我有一个错误的步骤。
感谢您的帮助。
守则-

class MaxPathSumBTree{

    class Node{
        Node left=null;
        Node right=null;;
        int val;
        Node(int v){ this.val=v;}
    }

    int maxsum=0;
    int curr_sum=0;
    List<int[]> paths=new ArrayList<int[]>();
    int[] currpath=new int[20];

    public MaxPathSumBTree(){
        .....
        processMaxPath(v,0);
    }

    private void maxSum(Node n,int maxsum,int curr_sum,int rank){

            if(n==null){
                if(curr_sum>maxsum==true){
                System.out.println("current : " + curr_sum + " maxsum : " + maxsum);
                    maxsum=curr_sum;
                    paths.add(0,currpath);
                }
                return;
            }
            currpath[rank]=n.val;
            curr_sum+=n.val;
            rank++;
            maxSum(n.left,maxsum,curr_sum,rank);
            maxSum(n.right,maxsum,curr_sum,rank);
    }
.......
     public static void main(String[] args){
        MaxPathSumBTree msbt=new MaxPathSumBTree();
        System.out.println("Final sum : " + msbt.maxsum  );

    }

}

输出-
Current node : 20 maxsum : 0
Current node : 8 maxsum : 0
Current node : 12 maxsum : 0
current : 40 maxsum : 40
current : 40 maxsum : 40
Current node : 15 maxsum : 0
current : 43 maxsum : 43
current : 43 maxsum : 43
Current node : 9 maxsum : 0
Current node : 17 maxsum : 0
current : 46 maxsum : 46
current : 46 maxsum : 46
Current node : 13 maxsum : 0
current : 42 maxsum : 42
current : 42 maxsum : 42

Final sum : 0

最佳答案

您正在修改局部变量(maxsum),而不是类字段(this.maxsum)
用“this.maxsum”代替“maxsum”

private void maxSum(Node n,int maxsum,int curr_sum,int rank){

        if(n==null){
          ...
            this.maxsum=curr_sum;
          ...
           }
        }

10-06 09:11