-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeMaximumPathSum.java
More file actions
38 lines (33 loc) · 1.08 KB
/
BinaryTreeMaximumPathSum.java
File metadata and controls
38 lines (33 loc) · 1.08 KB
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
// https://leetcode.com/problems/binary-tree-maximum-path-sum/
// #tree #dfs
/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode
* right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left,
* TreeNode right) { this.val = val; this.left = left; this.right = right; } }
*/
class Solution {
private int helper(TreeNode root, int[] result) {
if (root == null) return 0;
int left = helper(root.left, result);
int right = helper(root.right, result);
if (left + right + root.val > result[0]) {
result[0] = left + right + root.val;
}
if (left + root.val > result[0]) {
result[0] = left + root.val;
}
if (right + root.val > result[0]) {
result[0] = right + root.val;
}
if (root.val > result[0]) {
result[0] = root.val;
}
return Math.max(left + root.val, Math.max(right + root.val, root.val));
}
public int maxPathSum(TreeNode root) {
int[] result = new int[1];
result[0] = Integer.MIN_VALUE;
helper(root, result);
return result[0];
}
}