0.总结
- 这题真的是简单题吗?我写了一个小时硬是没写出来。。。。
- 关键问题在于不要弄错题目,是根节点到叶子节点。所以要判断一个节点是不是叶子节点,再判断是否满足路径和相等。
1. 题目
2. 分析
3. 代码
# 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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
return self.dfs(root,tmp=[],target=targetSum)
def dfs(self,root,tmp,target):
if root is None:
return False
if root.left is None and root.right is None:
if sum(tmp) + root.val == target: # 说明已经找到结果了
return True
return False
tmp.append(root.val)
if self.dfs(root.left,tmp,target) or self.dfs(root.right,tmp,target):
return True
tmp.pop()
return False