Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
解题思路:
遍历二叉树,以每一个节点为中心,来生成一个该节点的最大路径,因为需要大量重复计算,所以改进用val来存一些信息。
因为可过可不过根节点,所以遍历二叉树时需要做两件事:
1.生成以该节点m为根节点的一条最大路径,跟max比较,如果比max大 ,更新max
2.将左子树跟节点left和右子树根节点right的较大值找出来,如果比0大,则在该节点m的值上加上这个较大值(因为对于上层节点来说,下层节点的子树只能有一个作为路径的一部分,所以需要选一个较大值),递归即可。
public class Solution {
int max;
public int maxPathSum(TreeNode root) {
max = Integer.MIN_VALUE;
maxNode(root);
return max;
}
public int maxNode(TreeNode root){
int left,right,temp = 0;
if(root == null)
return 0;
left = maxNode(root.left);
right = maxNode(root.right);
if(left > 0 && right > 0) temp = root.val+left+right;
else if(left > 0) temp = root.val+left;
else if(right > 0) temp = root.val+right;
else temp = root.val;
max = Math.max(max, temp);
if((temp = Math.max(left, right)) > 0)
root.val += temp;
return root.val;
}
}