【leetcode】124. Binary Tree Maximum Path Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/86556472

Given a non-empty 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.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

思考:又是一道与二叉树相关的题目:求总和为最大的路径,与求最长相同值路径那道题有异曲同工之妙。可以采用自底向上的递归方式进行求解。

这里有一个坑:就是倘若有一棵子树的最大和为负数,那么,我们就可以直接丢弃该树了,可以使其为零而巧妙地达到这种效果

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int ans;
    public int maxPathSum(TreeNode root) {
        ans = Integer.MIN_VALUE;
        dfs(root);
        return ans;
    }
    
    public int dfs(TreeNode node){
        if(node == null){
            return 0;
        } else {
            //walk the tree
            int left = dfs(node.left);
            int right = dfs(node.right);
            if(left<0)
                left = 0;
            if(right<0)
                right = 0;
            //保存最大值
            ans = Math.max(ans,left + node.val + right);
            return Math.max(node.val,Math.max(left+node.val,node.val+right));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/ghscarecrow/article/details/86556472