-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path112_Path Sum.py
More file actions
44 lines (38 loc) · 1.26 KB
/
112_Path Sum.py
File metadata and controls
44 lines (38 loc) · 1.26 KB
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
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 17:28:29 2020
@author: leiya
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
0721
'''
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
def dfs(root,sum):
if not root:
return False
'''
注意符合要求的条件在于该node的左右都没有node了(意味着它是叶子节点,不加这个判断没办法确定是叶子节点)且他的值为sum
'''
if not root.left and not root.right and root.val == sum:
return True
else:
return dfs(root.left,sum-root.val) or dfs(root.right,sum-root.val)
if dfs(root,sum):
return True
else:
return False
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
else:
return self.hasPathSum(root.left,sum - root.val) or self.hasPathSum(root.right,sum-root.val)