import java.util.HashMap;
import java.util.Map;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
//当节点i不是根节点时,最大路径为 max(左子树的最大路径,右子树最大路径)+root.val
//当节点i是根节点时,经过i的最大路径为 左子树最大路径+右子树最大路径+root.val, 其中舍弃左右子树中为负的值,root节点不可舍弃
//最开始想的是遍历每一个节点i,求以i为根节点取最大值,在从这些最大值中取出真正最大的那一个,后来发现其实没必要
public int maxPathSum(TreeNode root) {
ans = Integer.MIN_VALUE;
compute(root);
return ans;
}
int ans = Integer.MIN_VALUE;
// public void search(TreeNode root) {
// if (root == null)
// return;
// if (root.left == null && root.right == null)
// ans = Math.max(ans, root.val);
//
// search(root.left);
// search(root.right);
//
// int left = compute(root.left);
// left = left < 0 ? 0 : left;
// int right = compute(root.right);
// right = right < 0 ? 0 : right;
// int temp = Math.max(Math.max(left, right) + root.val, left + right + root.val);
System.out.println(root.val + " " + left + " " + right);
// ans = Math.max(temp, ans);
//
// }
public int compute(TreeNode root) {
if (root == null)
return 0;
if (root.left == null && root.right == null) {
ans = Math.max(ans, root.val);
return root.val;
}
int left = compute(root.left);
int right = compute(root.right);
left = left < 0 ? 0 : left;
right = right < 0 ? 0 : right;
int temp = Math.max(Math.max(left, right) + root.val, left + right + root.val);
ans = Math.max(ans, temp);
return Math.max(left, right) + root.val;
}
//下面为测试代码
public static void main(String[] args) {
int[] array = {0};
Solution solution = new Solution();
TreeNode[] node_array = solution.array2tree(array);
int ans = solution.maxPathSum(node_array[0]);
System.out.println(ans);
}
public TreeNode[] array2tree(int[] array) {
TreeNode[] node_array = new TreeNode[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] != -1)
node_array[i] = (new Solution()).new TreeNode(array[i]);
else
node_array[i] = null;
}
for (int i = 0; i < array.length / 2; i++) {
if (node_array[i] == null)
continue;
if (i * 2 + 1 < array.length && node_array[i * 2 + 1] != null) {
node_array[i].left = node_array[i * 2 + 1];
}
if (i * 2 + 2 < array.length && node_array[i * 2 + 2] != null) {
node_array[i].right = node_array[i * 2 + 2];
}
}
return node_array;
}
public void show(TreeNode root) {
if (root == null)
return;
System.out.print(root.val + " ");
show(root.left);
show(root.right);
}
}