124 Binary Tree Maximum Path Sum

124. Binary Tree Maximum Path Sum

1. Question

Given a 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.
For example: Given the below binary tree,
1
1
2
/ \
3
2 3
Copied!
Return6.

2. Implementation

(1) DFS
1
class Solution {
2
public int maxPathSum(TreeNode root) {
3
int[] max = new int[1];
4
max[0] = Integer.MIN_VALUE;
5
findMaxPathSum(root, max);
6
return max[0];
7
}
8
9
public int findMaxPathSum(TreeNode node, int[] max) {
10
if (node == null) {
11
return 0;
12
}
13
14
int leftPathSum = Math.max(0, findMaxPathSum(node.left, max));
15
int rightPathSum = Math.max(0, findMaxPathSum(node.right, max));
16
17
max[0] = Math.max(max[0], node.val + leftPathSum + rightPathSum);
18
return node.val + Math.max(leftPathSum, rightPathSum);
19
}
20
}
Copied!

3. Time & Space Complexity

(1) DFS: 时间复杂度: O(n), 空间复杂度: O(h)