112. 路径总和

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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.first_vale = []
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root==None: return False
self.first_vale.append(root.val)
print(targetSum)
# 基线条件
if root.left==None and root.right==None and targetSum==self.first_vale[0]:
print("--- ")
return True
if root.left==None and root.right==None and targetSum!=self.first_vale[0]:
return False
if root.left:
targetSum -= root.left.val
if self.hasPathSum(root.left,targetSum):
return True
targetSum += root.left.val
if root.right:
targetSum -= root.right.val
if self.hasPathSum(root.right,targetSum):
return True
targetSum += root.right.val
return False