- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathBinaryTreeMaximumPathSum124.java
More file actions
Latest commit
53 lines (39 loc) · 1.31 KB
/
Copy pathBinaryTreeMaximumPathSum124.java
File metadata and controls
53 lines (39 loc) · 1.31 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Given a binary tree, find the maximum path sum.
*
* For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections.
* The path must contain at least one node and does not need to go through the root.
*
* For example:
* Given the below binary tree,
*
* 1
* / \
* 2 3
*
* Return 6.
*/
publicclassBinaryTreeMaximumPathSum124 {
privateintmaxSum;
publicintmaxPathSum(TreeNoderoot) {
maxSum = Integer.MIN_VALUE;
maxBranch(root);
returnmaxSum;
}
privateintmaxBranch(TreeNoderoot) {
if (root == null) return0;
intvalueLeft = Math.max(0, maxBranch(root.left));
intvalueRight = Math.max(0, maxBranch(root.right));
maxSum = Math.max(maxSum, root.val + valueLeft + valueRight);
returnMath.max(valueLeft, valueRight) + root.val;
}
publicstaticvoidmain(String[] args) {
BinaryTreeMaximumPathSum124btmps = newBinaryTreeMaximumPathSum124();
TreeNoderoot1 = newTreeNode(2);
root1.left = newTreeNode(1);
root1.right = newTreeNode(3);
TreeNoderoot2 = newTreeNode(-3);
System.out.println(btmps.maxPathSum(root1));
System.out.println(btmps.maxPathSum(root2));
}
}