博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
113.Path Sum II(append 和+的区别)
阅读量:4358 次
发布时间:2019-06-07

本文共 1212 字,大约阅读时间需要 4 分钟。

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

5     / \    4   8   /   / \  11  13  4 /  \    / \7    2  5   1

Return:

[

[5,4,11,2],
[5,8,4,5]]

# Definition for a binary tree node.class TreeNode:    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution:    def pathSum(self, root, sum):        """        :type root: TreeNode        :type sum: int        :rtype: List[List[int]]        """        res = []        if root is None:            return res        def findpath(a,root,sum):            # a.append(root.val)            a = a + [root.val]            if root.left is None and root.right is None and root.val==sum:                res.append(a)                # print('a:',a)                # print('res:',res)            if root.left:                findpath(a,root.left,sum-root.val)            if root.right:                findpath(a,root.right,sum-root.val)        findpath([],root,sum)        return res

使用append实际是修改一个列表,使用+实际是创建一个新的列表。

参考:

转载于:https://www.cnblogs.com/bernieloveslife/p/9761376.html

你可能感兴趣的文章
禅道项目管理系统整合Selenium IDE的思路
查看>>
网页数据交互!有很多可能不完善希望能提出来
查看>>
自家用的java小总结(2.4):类的知识的查漏补缺(内部类)
查看>>
Linux重定向与管道
查看>>
string.indexOf()和$.inArray()查找
查看>>
lamp :在Linux 下搭建apache、Mysql、php
查看>>
【编程题目】圆形是否和正方形相交☆
查看>>
1.Struts2简介和Struts2开发环境搭建
查看>>
2019 CCPC-Wannafly Winter Camp Day4(Div2, onsite)
查看>>
SAP CRM 集类型(Set Type)与产品层次(Product Hierarchy)
查看>>
spring mvc
查看>>
poj 3071 Football(线段树+概率)
查看>>
Python爬虫入门教程 26-100 知乎文章图片爬取器之二
查看>>
面试题39 二叉树的深度
查看>>
Linq update
查看>>
CSRF
查看>>
【计算机网络】OSI模型,TCPIP模型
查看>>
Token 认证的来龙去脉
查看>>
Oracle——视图
查看>>
No input file specified
查看>>