Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
属于动态规划问题,只不过这里需要传递的数据太多,特别是递归的时候,所以定义了数组,方便在函数里来回传递,起到全局变量的作用。
一共有三种:
1,局部最大值
2,第二种类型的局部最大值
3,全局最大值
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
int[] max = {Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE};//有两种类型的局部最大值,一种是max(root.val,root.val+root.left.val,root.right.val),一种是root.left.val+root.right.val+root.val,前一种会对父节点的最大值产生影响,而后一种可能会影响全局最大值,最后一个元素是全局最大值
inorder(root,max);
return max[2] >= max[1]? max[2]:max[1] ;
}
public int inorder(TreeNode root, int[] max){
if(root == null){
return 0;
}
if(root.left == null && root.right == null){//叶子节点
max[2] = max[2] >= root.val ? max[2] : root.val;
return root.val;
}
int left = inorder(root.left,max);
int right = inorder(root.right,max);
max[0] = root.val >= root.val + left ? (root.val >= root.val + right ? root.val : root.val + right ) : (left >= right ? root.val+left : root.val + right );
max[1] = max[1] >= root.val+left+right ? max[1] : root.val+left+right;//跟新第二类型的局部最大值
max[2] = max[2] >= max[0] ? max[2] : max[0]; //更新全局最大值
return max[0];
}
}
Runtime:
376 ms