FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-interview-patterns/java/Trees/MaximumPathSum.java at main · iamthatdev/coding-interview-patterns · GitHub
iamthatdev
/
coding-interview-patterns
Public
forked from
ByteByteGoHq/coding-interview-patterns
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-interview-patterns
/
java
/
Trees
/
MaximumPathSum.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
39 lines (35 loc) · 1.15 KB
Breadcrumbs
coding-interview-patterns
/
java
/
Trees
/
MaximumPathSum.java
Copy path
File metadata and controls
39 lines (35 loc) · 1.15 KB
Raw
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
import
DS
.
TreeNode
;
/*
// Definition of TreeNode:
class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
*/
public
class
MaximumPathSum
{
int
maxSum
=
Integer
.
MIN_VALUE
;
public
int
maxPathSum
(
TreeNode
root
) {
maxPathSumHelper
(
root
);
return
maxSum
;
}
private
int
maxPathSumHelper
(
TreeNode
node
) {
// Base case: null nodes have no path sum.
if
(
node
==
null
) {
return
0
;
}
// Collect the maximum gain we can attain from the left and right
// subtrees, setting them to 0 if they're negative.
int
leftSum
=
Math
.
max
(
maxPathSumHelper
(
node
.
left
),
0
);
int
rightSum
=
Math
.
max
(
maxPathSumHelper
(
node
.
right
),
0
);
// Update the overall maximum path sum if the current path sum is
// larger.
maxSum
=
Math
.
max
(
maxSum
,
node
.
val
+
leftSum
+
rightSum
);
// Return the maximum sum of a single, continuous path with the
// current node as an endpoint.
return
node
.
val
+
Math
.
max
(
leftSum
,
rightSum
);
}
}
Back
|
FazBrowse Home
|
New Git URL