如 leetcode 中,Sum Root to Leaf Numbers
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self, root, sums):
sums = sums * 10 + root.val
if (root.left) and not (root.right): return self.helper(root.left, sums)
elif (root.right) and not (root.left): return self.helper(root.right, sums)
elif (root.left) and (root.right): return self.helper(root.right, sums) + self.helper(root.left, sums)
else:
return sums
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
return self.helper(root, 0)
sums存放了各次递归的和
此外,对于“二叉树中和为某一值的路径”,可得代码
def Combination_Sum_Helper(self,root,sums, path, res):
if (sums - root.val == 0):
path += [root.val]
res.append(path)
elif (sums - root.val <0): return
else:
if root.left: self.Combination_Sum_Helper(root.left, sums - root.val, path + [root.val],res)
if root.right: self.Combination_Sum_Helper(root.right, sums - root.val, path + [root.val], res)
def Combination_Sum(self,root, sums):
if not root: return []
res = []
self.Combination_Sum_Helper(root,sums,[], res)
return res
这里同样使用了参数传递的方法。由于函数直接在最后返回res,因此除了走不通的路,不需要写return。