Skip to content

Commit f96ac86

Browse files
committed
problem: 0437 path sum III
1 parent 8589875 commit f96ac86

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# 0437. Path Sum III
2+
3+
* Difficulty: medium
4+
* Link: https://leetcode.com/problems/path-sum-iii/
5+
* Topics: DFS-BFS
6+
* highlight: 遍歷順序
7+
8+
# Clarification
9+
10+
1. Check the inputs and outputs
11+
12+
# Solution (DFS)
13+
14+
### Thought Process
15+
16+
- 每個點都當成一棵樹的 root
17+
- Implement
18+
19+
```python
20+
21+
```
22+
23+
24+
### Complexity
25+
26+
- Time complexity:
27+
- Space complexity:
28+
29+
# Improvement (DFS + HashMap)
30+
31+
### Thought Process
32+
33+
- HashMap 紀錄前面路徑合出現過的次數
34+
35+
![Untitled](./Untitled.png)
36+
37+
- Implement
38+
39+
```python
40+
# Definition for a binary tree node.
41+
# class TreeNode:
42+
# def __init__(self, val=0, left=None, right=None):
43+
# self.val = val
44+
# self.left = left
45+
# self.right = right
46+
class Solution:
47+
count = 0
48+
pathSumMap = {}
49+
pathSumMap[0]=1
50+
51+
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
52+
53+
if not root:
54+
return 0
55+
56+
def dfs(root, curSum):
57+
if not root:
58+
return
59+
curSum += root.val
60+
61+
# 計算路路徑長度差
62+
subPath = curSum - targetSum
63+
self.count += self.pathSumMap.get(subPath, 0)
64+
self.pathSumMap[curSum] = self.pathSumMap.get(curSum, 0) + 1
65+
66+
dfs(root.left, curSum)
67+
dfs(root.right, curSum)
68+
69+
# 換另一條路下去前,要把先前的路刪掉
70+
self.pathSumMap[curSum] = self.pathSumMap.get(curSum, 0) - 1
71+
curSum -= root.val
72+
73+
dfs(root, 0)
74+
75+
return self.count
76+
```
77+
78+
79+
### Complexity
80+
81+
- Time complexity:
82+
- Space complexity:
83+
84+
# Note

0437 Path Sum III/Untitled.png

359 KB
Loading

0 commit comments

Comments
 (0)