Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 69c8580

Browse files
committed
feat: finish path sum in python
1 parent e2fa15e commit 69c8580

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎alternative/easy/path_sum.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class TreeNode:
2+
def __init__(self, x):
3+
self.val = x
4+
self.left = None
5+
self.right = None
6+
7+
def has_path_sum(root, sum):
8+
if root is None:
9+
return False
10+
11+
stack = [(root, sum)]
12+
13+
while stack:
14+
node, curr_sum = stack.pop()
15+
if node.left is None and node.right is None and node.val == curr_sum:
16+
return True
17+
if node.left is not None:
18+
stack.append((node.left, curr_sum - node.val))
19+
if node.right is not None:
20+
stack.append((node.right, curr_sum - node.val))
21+
return False
22+
23+
# Test case
24+
t1 = TreeNode(5)
25+
t2 = TreeNode(4)
26+
t3 = TreeNode(8)
27+
t4 = TreeNode(11)
28+
t6 = TreeNode(4)
29+
t7 = TreeNode(7)
30+
t8 = TreeNode(2)
31+
t9 = TreeNode(1)
32+
t6.right = t9
33+
t4.right = t8
34+
t4.left = t7
35+
t3.right = t6
36+
t2.left = t4
37+
t1.right = t3
38+
t1.left = t2
39+
assert has_path_sum(t1, 22) == True

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /