在二叉树中计算最大总和时发出问题

时间:2015-02-18 10:29:19

标签: java algorithm binary-tree

我不知道为什么以及如何在迭代期间将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

1 个答案:

答案 0 :(得分:2)

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

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

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