Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
判断树是否存在一条根到叶子的路径使得其路径和等于给定的值~还是用递归来做,结束条件为:如果节点为空,则返回False;如果节点是叶节点并且剩余的sum等于当前叶节点的值,则返回True~ 代码如下~
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
if root is None: return False
if root.left is None and root.right is None and root.val == sum: return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
还有一种非递归解法,用栈来做~
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
if root is None: return False
stack = [(root, sum)]
while stack:
node, remainder = stack.pop()
if not node.left and not node.right:
if node.val == remainder:
return True
remainder -= node.val
if node.right:
stack.append((node.right, remainder))
if node.left:
stack.append((node.left, remainder))
return False