给定一棵二叉树和一个总数,判断树中是否存在从根结点到叶子节点的累加值等于该给定的总数
注意:叶子节点没有子树
Example:
Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1return true, as there exist a root-to-leaf path
5->4->11->2
which sum is 22.
1:递归,从最左边的路径开始,一旦满足要求就返回True
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
return self.recursionEachPath(root, 0, sum)
def recursionEachPath(self, node, curSum, sum):
if not node:
return curSum==sum
if not node.left and node.right is not None:
return self.recursionEachPath(node.right, curSum+node.val, sum)
if node.left is not None and not node.right:
return self.recursionEachPath(node.left, curSum+node.val, sum)
left = self.recursionEachPath(node.left, curSum+node.val, sum)
right = self.recursionEachPath(node.right, curSum+node.val, sum)
return left or right
该方法优化之后的代码为(参考他人代码):
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:
return root.val==sum
if not root.right:
return self.hasPathSum(root.left, sum-root.val)
if not root.left:
return self.hasPathSum(root.right, sum-root.val)
return self.hasPathSum(root.right, sum-root.val) or self.hasPathSum(root.left, sum-root.val)
2:先找到所有路径的各自总和,然后判断给定的总和是否存在
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
if sum in self.allPathesSum(root):
return True
else:
return False
def allPathesSum(self, root):
if not root.left and not root.right: #递归结束的标志
return [root.val]
elif not root.right:
tempList = self.allPathesSum(root.left)
elif not root.left:
tempList = self.allPathesSum(root.right)
else:
left = self.allPathesSum(root.left)
right = self.allPathesSum(root.right)
tempList = left + right
for i in range(len(tempList)): #累加该结点的值
tempList[i] += root.val
return tempList
3:迭代
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
allPathesSum = [[root,root.val]]
while allPathesSum:
curNode = allPathesSum.pop()
if not curNode[0].left and not curNode[0].right:
if curNode[1]==sum:
return True
elif not curNode[0].left:
allPathesSum.insert(0,[curNode[0].right,curNode[0].right.val+curNode[1]])
elif not curNode[0].right:
allPathesSum.insert(0,[curNode[0].left,curNode[0].left.val+curNode[1]])
else:
allPathesSum.insert(0,[curNode[0].left,curNode[0].left.val+curNode[1]])
allPathesSum.insert(0,[curNode[0].right,curNode[0].right.val+curNode[1]])
return False
算法题来自:https://leetcode-cn.com/problems/path-sum/description/