-
Notifications
You must be signed in to change notification settings - Fork 171
/
BinaryTreeMaximumPathSum.java
43 lines (41 loc) · 1.1 KB
/
BinaryTreeMaximumPathSum.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Author: Andy, [email protected]
Date: Jan 28, 2015
Problem: Binary Tree Maximum Path Sum
Difficulty: Easy
Source: https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/
Notes:
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
Solution: Recursion...
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
int[] res = new int[1];
res[0] = Integer.MIN_VALUE;
maxPathSumRe(root, res);
return res[0];
}
int maxPathSumRe(TreeNode root, int[] res) {
if (root == null) return 0;
int left = maxPathSumRe(root.left, res);
int right = maxPathSumRe(root.right, res);
res[0] = Math.max(res[0], root.val + Math.max(left, 0) + Math.max(right, 0));
return Math.max(root.val, root.val + Math.max(left, right));
}
}