Binary Tree Maximum Path Sum


算法:二叉树 + 动态规划

url:https://leetcode.com/problems/binary-tree-maximum-path-sum/

题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
124. Binary Tree Maximum Path Sum
Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

1
/ \
2 3

Output: 6
Example 2:

Input: [-10,9,20,null,null,15,7]

-10
/ \
9 20
/ \
15 7

Output: 42

分析:

不要求 最大值的路径,只要求最大值

Java解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
int ret = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
return maxSum(root);
}
public int maxSum(TreeNode root) {
if (null == root) return 0;
int l = Math.max(0, maxSum(root.left));
int r = Math.max(0, maxSum(root.right));
int sum = l + r + root.val;
ret = Math.max(ret, sum);
return Math.max(l, r) + root.val;
}
}