0%

Leetcode124-binaryTreeMaximumPathSum

Description

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

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

Solution

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 {
private int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root){
if (root == null) return 0;
travelsal(root);
return res;
}

public int travelsal(TreeNode node){
if (node == null) return 0;

int left = Math.max(travelsal(node.left), 0);
int right = Math.max(travelsal(node.right), 0);
res = Math.max(res, left + right + node.val);
return Math.max(left, right) + node.val;
}
}