[英]Issue while calculating max sum in a binary tree
I am not sure why and how is the maxsum getting reset to 0 during the iteration. 我不确定在迭代过程中maxsum为什么以及如何重置为0。
There is some step I am erring in calculating the max sum to the leaf. 在计算叶子的最大总和时,我有些错误。 Help is appreciated.
感谢帮助。
The code - 编码 -
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 );
}
}
Output - 输出-
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
You are modifying local variable (maxsum), not class field (this.maxsum) Use "this.maxsum" instaead of "maxsum" 您正在修改局部变量(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;
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.