题目地址
https://leetcode-cn.com/problems/path-sum
题目描述
代码初步
- 思路:递归
这里采用sum 倒减的方式,利用递归,遍历整棵树:会出现如下两种情况 1.如果当前节点不是叶子,对它的所有孩子节点,递归调用 hasPathSum 函数,其中 sum 值减去当前节点的权值;
2.如果当前节点是叶子,检查 sum 值是否为 0,也就是是否找到了给定的目标和。
代码欣赏
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
sum -= root.val
# 左右结点都为空,判断是否与sum相等
if not root.left and not root.right:
return sum == 0
return self.hasPathSum(root.left,sum) or self.hasPathSum(root.right,sum)