offer2-51


路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给定一个二叉树的根节点 root ,返回其 最大路径和,即所有路径上节点值之和的最大值。

示例 1:

img

输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6

示例 2:

img

输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42

提示:

  • 树中节点数目范围是 [1, 3 * 104]
  • -1000 <= Node.val <= 1000

//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private Map<TreeNode, Integer> maxPathSumMap;

    private Map<TreeNode, Integer> maxPathMap;

    public int maxPathSum(TreeNode root) {
        maxPathSumMap = new HashMap<>();
        maxPathMap = new HashMap<>();
        return getMaxPathSum(root);
    }

    private int getMaxPathSum(TreeNode node) {
        if (node == null) {
            return Integer.MIN_VALUE;
        }

        if (maxPathSumMap.containsKey(node)) {
            return maxPathSumMap.get(node);
        }

        int result = Integer.MIN_VALUE;

        int leftMax = getMaxPathSum(node.left);
        if (leftMax > result) {
            result = leftMax;
        }
        int rightMax = getMaxPathSum(node.right);
        if (rightMax > result) {
            result = rightMax;
        }

        int mid = node.val + getMaxPath(node.left) + getMaxPath(node.right);
        if (mid > result) {
            result = mid;
        }

        maxPathSumMap.put(node, result);
        return result;
    }

    private int getMaxPath(TreeNode node) {
        if (node == null) {
            return 0;
        }

        if (maxPathMap.containsKey(node)) {
            return maxPathMap.get(node);
        }

        int left = getMaxPath(node.left);
        int right = getMaxPath(node.right);
        int result = node.val;
        if (left > right && left > 0) {
            result += left;
        } else if (right > left && right > 0) {
            result += right;
        }

        if (result < 0) {
            result = 0;
        }
        maxPathMap.put(node, result);
        return result;
    }

}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !