问题描述:
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
返回 true
, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2
。
错误:
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
def preOrder(self,root,sum,temp_sum):
if self.flag:
return self.flag
elif root and not self.flag:
temp_sum += root.val
if not root.left and not root.right:
if sum == temp_sum:
self.flag = True
return
else :
temp_sum -= root.val
self.flag = False
if root == None:
return
preOrder(self,root.left,sum,temp_sum)
preOrder(self,root.right,sum,temp_sum)
self.flag = False
return preOrder(self,root,sum,0)
改正:
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
self.flag = False
def preOrder(self,root,sum,temp_sum):
if not self.flag:
if root:
temp_sum += root.val
if root.left or root.right:
preOrder(self,root.left,sum,temp_sum)
preOrder(self,root.right,sum,temp_sum)
else:
if sum == temp_sum:
self.flag = True
else:
temp_sum -= root.val
if root:
preOrder(self,root,sum,0)
return self.flag
参考:
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
self.flag = False
def dfs(node,sumNow = 0,target = sum):
if not self.flag:
if node:
sumNow += node.val
if node.left or node.right:
dfs(node.left, sumNow, target)
dfs(node.right, sumNow, target)
else:
if sumNow == target:
self.flag = True
if root:
dfs(root)
return self.flag
官方:
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
if root.left is None and root.right is None:
return root.val == sum
if root.left == None:
return self.hasPathSum(root.right,sum - root.val)
if root.right == None:
return self.hasPathSum(root.left,sum - root.val)
return self.hasPathSum(root.left,sum - root.val) or self.hasPathSum(root.right,sum - root.val)
2018-09-10 20:54:47