124. 二叉树中的最大路径和 - 【递归/DFS/后序遍历】

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

** 路径可以从某个子节点向上经过父节点穿到另一个子树,但不可以再穿回来

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    Integer max;

    public int maxPathSum(TreeNode root) {
        subMaxPathSum(root);
        return max;
    }

    private int subMaxPathSum(TreeNode root) {
        if (root == null) return 0;

    // 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值,如果某个子树贡献值为负数,就不要走这个子树,贡献值即变为0
int leftSubMax = Math.max(0, subMaxPathSum(root.left)); int rightSubMax = Math.max(0, subMaxPathSum(root.right)); int result = root.val + leftSubMax + rightSubMax;

    // max是最终结果,即遍历过程中最长的路径
if (max == null || result > max) {
            max = result;
        }

    // 某个节点的最大贡献值 = 这个节点的值 + 其左/右子树的最大贡献值
return root.val + Math.max(leftSubMax, rightSubMax); } }

猜你喜欢

转载自www.cnblogs.com/svtforever/p/13396324.html