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.

 


对于树,我们可以找到其左右子树中终止于根节点的最大路径值,称为最大半路径值,如果都是正数,则可以把它们以及根节点值相加,如果其中有负数,则舍弃那一边的值(即置为零)。如此可以找到包含根节点的最大路径值。然后选择左右子树的最大半路径值中大的那个(负数则置为0)加上根节点的值作为新的最大半路径值传给父节点。

于是我们可以递归地考察每个子树,不断更新一个全局变量max。

基本情况为:子树为null,此时最大路径值应为0.

代码如下:

 1     int max;
 2     public int maxPathSum(TreeNode root) {
 3         max = root==null?0:root.val;
 4         findMax(root);
 5         return max;
 6     }
 7     public int findMax(TreeNode root) {
 8         if(root==null)
 9             return 0;
10         int left = Math.max(findMax(root.left),0);
11         int right = Math.max(findMax(root.right),0);
12         max = Math.max(max, left+right+root.val);
13         return Math.max(left, right) + root.val;
14     }

 

 

posted on 2014-11-19 00:34  metalx  阅读(125)  评论(0编辑  收藏  举报