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 must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
求二叉树任意起止点构成的路径的值最大和
虽然是任意起止点,但此路径一定会有根节点,因此对于该根节点:
max = root.val+maxPathSum(左子树)(>0才加)+maxPathSum(右子树)(>0才加);
但对于每次递归的返回,则应该是
return max(root.val,root.val+maxPathSum(左子树),root.val+maxPathSum(右子树));
public static int max;
public static int maxPathSum(TreeNode root) {
if(root==null)
return 0;
max = Integer.MIN_VALUE;
maxPathSum2(root);
return max;
}
public static int maxPathSum2(TreeNode root) {
if(root==null)
return 0;
int temp1 = maxPathSum2(root.left);
int temp2 = maxPathSum2(root.right);
int temp = root.val;
if(temp1>0)temp+=temp1;
if(temp2>0)temp += temp2;
max = temp>max?temp:max;
return max(root.val,root.val+temp1,root.val+temp2);
}
public static int max(int i,int j,int k){
return i > (j>k?j:k) ? i : (j>k?j:k);
}