if not root: #节点为空,false
return False
if not root.left and not root.right: #判断叶子结点值
return root.val==targetSum
return self.hasPathSum(root.left,targetSum-root.val) or self.hasPathSum(root.right,targetSum-root.val) #左右有一条就TRUE
2)可以采用BFS搜索
使用队列保存路径和,若和等于目标值并且该节点是叶子结点,TRUE
这种方法更具体,把每一个节点的值都计算出来判断
if not root: #空节点false
return False
que = collections.deque() #使用队列
que.append((root,root.val))
while que:
node,zhi = que.popleft() #将和从头开始加到变量zhi里
if not node.left and not node.right and zhi == targetSum: #对比并判断是否叶子
return True
if node.left:
que.append((node.left,zhi+node.left.val)) #计算到达每一个节点和
if node.right:
que.append((node.right,zhi+node.right.val))
return False