0124. Binary Tree Maximum Path Sum (H)

Binary Tree Maximum Path Sum (H)

题目

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node's values in the path.

Given the root of a binary tree, return the maximum path sum of any path.

Example 1:

Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Example 2:

Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

Constraints:

  • The number of nodes in the tree is in the range [1, 3 * 10^4].
  • -1000 <= Node.val <= 1000

题意

给定一个二叉树,在树中找到任意一条路径(起点随意,终点随意),使得这条路径上结点值的和最大。


思路

递归处理。对于一个以 root 为根结点的子树,我们计算以 root.left 为起点并向下延伸的路径的最大和 a,以及以 root.right 为起点并向下延伸的路径的最大和 b,将 a, b, root.val 相加就得到了经过 root 的路径的最大和。对每一个结点都做相同的处理,就得到了全局最大路径和。由此可以定义我们的递归函数 int dfs(TreeNode root),其返回值是以 root 为起点并向下延伸的路径的最大和,dfs(root.left) + dfs(root.right) + root.val 为经过 root 的最大路径和。注意负数值的处理。


代码实现

Java

class Solution {
    private int maxSum;

    public int maxPathSum(TreeNode root) {
        maxSum = Integer.MIN_VALUE;
        dfs(root);
        return maxSum;
    }

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

        int leftPathSum = Math.max(dfs(root.left), 0);
        int rightPathSum = Math.max(dfs(root.right), 0);

        maxSum = Math.max(maxSum, leftPathSum + rightPathSum + root.val);
      
        return Math.max(leftPathSum, rightPathSum) + root.val;
    }
}
posted @ 2021-08-26 23:14  墨云黑  阅读(23)  评论(0编辑  收藏  举报