说明: 叶子节点是指没有子节点的节点。
思路:只想到了使用递归的方法,递归查找左右子树是否存在和 sum - root.val 的一条路径,结束条件是节点为叶节点且其值为sum,还需要注意树为空的情况(这里应该用到了分治法的思想),下面是python实现:
# 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 root == None:
return False
#处理叶节点的情况
if root.left == None and root.right == None:
if sum == root.val:
return True
else:
return False
#递归遍历左右子树
if root.left != None or root.right != None:
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)
python刚开始学,还请大佬们多多指教!!