File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ package leetcode ;
2+
3+ /**
4+ * Project Name : Leetcode
5+ * Package Name : leetcode
6+ * File Name : BinaryTreeMaximumPathSum
7+ * Creator : Leo
8+ * Description : 124. Binary Tree Maximum Path Sum
9+ */
10+ public class BinaryTreeMaximumPathSum {
11+ /**
12+ * Given a binary tree, find the maximum path sum.
13+
14+ For this problem, a path is defined as any sequence of nodes from some starting node to any node
15+ in the tree along the parent-child connections. The path must contain at least one node and does not
16+ need to go through the root.
17+
18+ For example:
19+ Given the below binary tree,
20+
21+ 1
22+ / \
23+ 2 3
24+ Return 6.
25+
26+ 3
27+ / \
28+ 9 20
29+ / \
30+ 15 7
31+
32+
33+ time : O(n)
34+ space : O(n)
35+
36+ */
37+
38+ int res ;
39+
40+ public int maxPathSum (TreeNode root ) {
41+ if (root == null ) return 0 ;
42+ res = Integer .MIN_VALUE ;
43+ helper (root );
44+ return res ;
45+ }
46+ public int helper (TreeNode root ) {
47+ if (root == null ) return 0 ;
48+ int left = Math .max (0 , helper (root .left ));
49+ int right = Math .max (0 , helper (root .right ));
50+ res = Math .max (res , left + right + root .val );
51+ return Math .max (left , right ) + root .val ;
52+ }
53+ }
You can’t perform that action at this time.
0 commit comments