124. Binary Tree Maximum Path Sum

来源:互联网 发布:淘宝售后客服话术大全 编辑:程序博客网 时间:2024/06/05 20:08

1.定义maxDeep(x)为以x为根节点的树的max path

   maxDeep(x)等于在下面a,b,c中找到一个最大的值,c的话是因为左子树的max path 和 右子树的max path可能值为负

   a.左子树的max path  + x自身的值

   b.右子树的max path  + x自身的值

   c.x自身的值


/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int ans = Integer.MIN_VALUE;    int maxDeep(TreeNode root){        if(root == null) return 0;        int curAns = root.val;        int lMax = maxDeep(root.left);        int rMax = maxDeep(root.right);        if(lMax > 0 ){            curAns += lMax;        }        if(rMax >0){            curAns += rMax;        }        if(curAns > ans){            ans =  curAns;        }                  return  Math.max(root.val,Math.max(root.val+lMax,root.val+rMax));    }    public int maxPathSum(TreeNode root) {                maxDeep(root);        return ans;            }}


原创粉丝点击