leetcode-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:

1
2
3
4
5
6
7
Input: [1,2,3]

1
/ \
2 3

Output: 6

Example 2:

1
2
3
4
5
6
7
8
9
Input: [-10,9,20,null,null,15,7]

-10
/ \
9 20
/ \
15 7

Output: 42

分析


二叉树里路径可以从任意节点开始到任意节点结束,二叉树可以用 DFS 来遍历,先算出左右子树的结果 left, right, 如果大于0,则对结果有利,加上 left 或 right 后与之前的 max 进行比较,取较大值。

解决方案1(Python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.maxSum = float("-inf")

def maxPathSum(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if not node:
return 0
left = max(dfs(node.left), 0)
right = max(dfs(node.right), 0)

self.maxSum = max(self.maxSum, node.val + left + right)
return node.val + max(left, right)
dfs(root)
return self.maxSum

解决方案1(Java)


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
26
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return max;
}

private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int left = Math.max(dfs(root.left), 0);
int right = Math.max(dfs(root.right), 0);
max = Math.max(max, root.val + left + right);
return root.val + Math.max(left, right);
}
}

相关问题


题目来源