题目

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:

image.png

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

Example 2:

image.png

  1. Input: root = [-10,9,20,null,null,15,7]
  2. Output: 42
  3. 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

  1. class Solution {
  2. private int maxSum;
  3. public int maxPathSum(TreeNode root) {
  4. maxSum = Integer.MIN_VALUE;
  5. dfs(root);
  6. return maxSum;
  7. }
  8. private int dfs(TreeNode root) {
  9. if (root == null) {
  10. return 0;
  11. }
  12. int leftPathSum = Math.max(dfs(root.left), 0);
  13. int rightPathSum = Math.max(dfs(root.right), 0);
  14. maxSum = Math.max(maxSum, leftPathSum + rightPathSum + root.val);
  15. return Math.max(leftPathSum, rightPathSum) + root.val;
  16. }
  17. }