File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
Lintcode/src/chapter3_binary_tree_and_divide_and_conquer Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ package chapter3_binary_tree_and_divide_and_conquer ;
2
+
3
+ import classes .TreeNode ;
4
+
5
+ public class BinaryTreeMaximumPathSum {
6
+
7
+ //used the approach that jiuzhang officially explained, pretty cool!
8
+ //create a new class to store two pieces of information, this makes things a lot easier!
9
+
10
+ /**
11
+ * @param root: The root of binary tree.
12
+ * @return: An integer.
13
+ */
14
+ public int maxPathSum (TreeNode root ) {
15
+ return dfs (root ).maxPath ;
16
+ }
17
+
18
+ ResultType dfs (TreeNode root ){
19
+ //exit
20
+ if (root == null ){
21
+ return new ResultType (0 , Integer .MIN_VALUE );
22
+ }
23
+
24
+ //divide
25
+ ResultType left = dfs (root .left );
26
+ ResultType right = dfs (root .right );
27
+
28
+ //conquer
29
+ int singlePath = Math .max (left .singlePath , right .singlePath ) + root .val ;
30
+ singlePath = Math .max (0 , singlePath );
31
+
32
+ int maxPath = Math .max (left .maxPath , right .maxPath );
33
+ maxPath = Math .max (maxPath , left .singlePath + right .singlePath + root .val );
34
+
35
+
36
+ return new ResultType (singlePath , maxPath );
37
+
38
+ }
39
+
40
+ class ResultType {
41
+ int maxPath ;
42
+ int singlePath ;
43
+ ResultType (int singlePath , int maxPath ){
44
+ this .maxPath = maxPath ;
45
+ this .singlePath = singlePath ;
46
+ }
47
+ }
48
+
49
+ }
You can’t perform that action at this time.
0 commit comments