FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/437_Path_Sum_III.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
java
/
437_Path_Sum_III.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
37 lines (30 loc) · 1.42 KB
Breadcrumbs
leetcode
/
java
/
437_Path_Sum_III.java
Copy path
File metadata and controls
37 lines (30 loc) · 1.42 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
/*
https://leetcode.com/problems/path-sum-iii/
You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a
given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only
from parent nodes to child nodes).
Maintain a mapping from all sums on the current path to their counts. For each node, add to paths count if the
difference between partial sum to this node and some earlier path sum from mapping equals target. Increment current
partial sum in mapping and recurse left and right. Decrement partial sum count after recursing.
Time - O(n)
Space - O(n)
*/
public
class
Solution
{
Map
<
Integer
,
Integer
>
path_sums
=
new
HashMap
<
Integer
,
Integer
>();
public
int
pathSum
(
TreeNode
root
,
int
sum
) {
path_sums
.
put
(
0
,
1
);
// default one count of zero sum
return
helper
(
root
,
0
,
sum
);
}
public
int
helper
(
TreeNode
node
,
int
partial
,
int
target
) {
if
(
node
==
null
)
return
0
;
int
paths
=
0
;
partial
+=
node
.
val
;
if
(
path_sums
.
containsKey
(
partial
-
target
))
paths
+=
path_sums
.
get
(
partial
-
target
);
path_sums
.
put
(
partial
,
path_sums
.
getOrDefault
(
partial
,
0
) +
1
);
paths
+=
helper
(
node
.
left
,
partial
,
target
) +
helper
(
node
.
right
,
partial
,
target
);
path_sums
.
put
(
partial
,
path_sums
.
get
(
partial
) -
1
);
return
paths
;
}
}
Back
|
FazBrowse Home
|
New Git URL