Skip to content

Commit daa7898

Browse files
Lintcode/src/chapter3_binary_tree_and_divide_and_conquer/BinaryTreeMaximumPathSum.java
1 parent ff7777f commit daa7898

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
}

0 commit comments

Comments
 (0)