54 lines
1.5 KiB
Java
54 lines
1.5 KiB
Java
package com.hong.www;
|
|
|
|
import java.util.ArrayList;
|
|
|
|
public class A124 {
|
|
public int aaa(TreeNode root,ArrayList<Integer> numbers) {
|
|
int right=0;
|
|
int left=0;
|
|
if(root.right != null){
|
|
right=aaa(root.right,numbers);
|
|
};
|
|
if(root.left!=null){
|
|
left=aaa(root.left,numbers);
|
|
}
|
|
if(left>0&&right>0){
|
|
numbers.add(left+right+root.val);
|
|
}else if(left>0){
|
|
numbers.add(left+root.val);
|
|
}else if(right>0){
|
|
numbers.add(right+root.val);
|
|
}else{
|
|
numbers.add(root.val);
|
|
}
|
|
//numbers.add(left+right+root.val);
|
|
if(right>left&&right>0){
|
|
return right+root.val;
|
|
}else if(left>right&&left>0){
|
|
return left+root.val;
|
|
}else{
|
|
return root.val;
|
|
}
|
|
//return right+left+root.val;
|
|
}
|
|
public int maxPathSum(TreeNode root){
|
|
ArrayList<Integer> numbers=new ArrayList<>();
|
|
int finalcount=Integer.MIN_VALUE;
|
|
aaa(root,numbers);
|
|
for(int x:numbers){
|
|
if(x>finalcount){
|
|
finalcount=x;
|
|
}
|
|
}
|
|
return finalcount;
|
|
}
|
|
public static void main(String[] args) {
|
|
TreeNode root = new TreeNode(1);
|
|
root.left = new TreeNode(1);
|
|
root.right = new TreeNode(100);
|
|
root.right.left = new TreeNode(2);
|
|
root.right.right=new TreeNode(2);
|
|
A124 solution = new A124();
|
|
System.out.println(solution.maxPathSum(root));
|
|
}
|
|
} |