We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent e2fa15e commit 69c8580Copy full SHA for 69c8580
alternative/easy/path_sum.py
@@ -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
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
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments