在二叉树中计算最大和时出现问题
Issue while calculating max sum in a binary tree
我不确定为什么以及如何在迭代期间将最大值重置为 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),而不是 class 字段 (this.maxsum)
使用 [=g13=] 而不是 "maxsum"
private void maxSum(Node n,int maxsum,int curr_sum,int rank){
if(n==null){
...
this.maxsum=curr_sum;
...
}
}
我不确定为什么以及如何在迭代期间将最大值重置为 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),而不是 class 字段 (this.maxsum) 使用 [=g13=] 而不是 "maxsum"
private void maxSum(Node n,int maxsum,int curr_sum,int rank){
if(n==null){
...
this.maxsum=curr_sum;
...
}
}