题目描述
判断一棵树中有没有一条路径,其和等于给定值。
思路
用深度优先搜索(DFS)遍历树的所有结点的值,要注意每深一层要从中减去相应节点的值。
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
if not root.left and not root.right:
if root.val == sum:
return True
else:
return False
else:
return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)