GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode-2/java/437_Path_Sum_III.java at master · st-rnd/leetcode-2

Expand file tree

/

437_Path_Sum_III.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
47 lines (44 loc) · 1.56 KB
/

437_Path_Sum_III.java

Copy path

File metadata and controls

47 lines (44 loc) · 1.56 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
40
41
42
43
44
45
46
47
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
/*public int pathSum(TreeNode root, int sum) {
if (root != null) return findPaths(root, sum)
+ pathSum(root.left, sum)
+ pathSum(root.right, sum);
return 0;
}
private int findPaths(TreeNode root, int target) {
if (root != null) return (root.val == target? 1 : 0)
+ findPaths(root.left, target - root.val)
+ findPaths(root.right, target - root.val);
return 0;
}*/
private int result;
private HashMap<Integer, Integer> cache;
public int pathSum(TreeNode root, int sum) {
result = 0;
cache = new HashMap<Integer, Integer>();
cache.put(0, 1);
pathSumHelper(root, sum, 0);
return result;
}
// https://leetcode.com/problems/path-sum-iii/discuss/91892/Python-solution-with-detailed-explanation
private void pathSumHelper(TreeNode root, int target, int soFar) {
if (root != null) {
int complement = soFar + root.val - target;
if (cache.containsKey(complement))
result += cache.get(complement);
cache.put(soFar + root.val, cache.getOrDefault(soFar + root.val, 0) + 1);
pathSumHelper(root.left, target, soFar + root.val);
pathSumHelper(root.right, target, soFar + root.val);
cache.put(soFar + root.val, cache.get(soFar + root.val) - 1);
}
}
}
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.