leetcode 124. 二叉树中的最大路径和【DFS】

套用二叉树后序遍历的递归代码,计算某一节点左、右子树的最大路径和后,再与该节点数值相加得到该节点及其左右子树的最大路径和。难点在于如何返回上一层递归调用中,因为若该路径和不是最大路径和时,则表示该节点的左、右子树只有一个能向上一层传递。

这里定义一个实例域记录每一层递归所产生的的最大路径和,因此递归函数在返回时只需要返回左、右子树中最大的路径和即可。

class Solution {
    int max = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        getMax(root);
        return max;
    }
    public int getMax(TreeNode root){
        if(root == null)return 0;
        int lmax = Math.max(getMax(root.left), 0);
        int rmax = Math.max(getMax(root.right), 0);
        int sum = root.val + lmax + rmax;
        max = max > sum?max:sum;
        return root.val + Math.max(lmax, rmax);
    }
}
发布了55 篇原创文章 · 获赞 0 · 访问量 788

猜你喜欢

转载自blog.csdn.net/er_ving/article/details/104724586