递归中子函数值传递的一种方法——参数传递

如 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。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值