leetcode-113 路径之和
题目描述:
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
解法一:找出所有路径,依次判断
# 注意函数名和变量名字冲突
class Solution:
def pathSum(self, root: TreeNode, sum_: int) -> List[List[int]]:
self.res = []
self.findPath(root,[])
return [v for v in self.res if sum(v)==sum_]
def findPath(self,root,path):
if not root:
return
if not root.left and not root.right:
path.append(root.val)
self.res.append(path)
return
self.findPath(root.left,path+[root.val])
self.findPath(root.right,path+[root.val])
解法二:直接判断,满足就加进去,速度比第一个慢
class Solution:
def pathSum(self, root: TreeNode, sum_: int) -> List[List[int]]:
self.res = []
self.findPath(root,[],sum_)
return self.res
def findPath(self,root,path,sum_):
if not root:
return
if not root.left and not root.right and root.val==sum_:
# path.append(root.val)
self.res.append(path+[root.val])
return
self.findPath(root.left,path+[root.val],sum_-root.val)
self.findPath(root.right,path+[root.val],sum_-root.val)
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
if not root:
return []
self.path = []
self.tmp = sum
def calSum(tmp_path,now,root):
if not root:
return False
if not root.left and not root.right and root.val + now== self.tmp:
self.path.append(tmp_path+[root.val])
if root.left:
calSum(tmp_path+[root.val],now+root.val,root.left)
if root.right:
calSum(tmp_path+[root.val],now+root.val,root.right)
calSum([],0,root)
return self.path