Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
43 lines (41 loc) · 1.1 KB

File metadata and controls

43 lines (41 loc) · 1.1 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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, nkuwjg@gmail.com
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));
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.