124-二叉树最大路径和

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

Description:

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,
这里写图片描述
Return 6.


问题描述:

给定二叉树,返回最大路径和
对于这个问题,序列被定义为通过父子连接由一个起始节点到终止节点的任意序列。路径至少有一个节点,并且不必经过根节点


问题分析:

通过后序遍历获取左右路径中最大的路径和(注意路径之和若小于0则置为0),然后与根节点组合形成最大路径和,若大于res,则更新res


解法

class Solution {
    int res = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        if(root == null)    return 0;

        DFS(root);

        return res;
    }
    public int DFS(TreeNode root){
        if(root == null)    return 0;

        int left = Math.max(0, DFS(root.left));
        int right = Math.max(0, DFS(root.right));

        res = Math.max(res, left + right + root.val);

        return root.val + Math.max(left, right);
    }
}
阅读更多

没有更多推荐了,返回首页