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]
] Time: O(N)
Space: O(Height)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res, lst = [], []
self.helper(root, sum, res, lst)
return res def helper(self, root, sum, res, lst):
if root is None:
return
if root.left is None and root.right is None:
if sum == root.val:
lst.append(root.val)
res.append(list(lst))
lst.pop()
return
lst.append(root.val)
left = self.helper(root.left, sum - root.val, res, lst)
right = self.helper(root.right, sum - root.val, res, lst)
lst.pop()

最新文章

  1. jquery 购物车飞入效果
  2. JMS
  3. php 读取网页源码 , 导出成txt文件, 读取xls,读取文件夹下的所有文件的文件名
  4. jquery工具方法proxy
  5. SVM 最大间隔目标优化函数(NG课件2)
  6. django模型
  7. \n 与 \r
  8. UltraEdit-32 恢复到初始默认配置
  9. WCF技术剖析之二十七: 如何将一个服务发布成WSDL[编程篇]
  10. Entity Framework Core 2.0 数据库迁移
  11. C# 文件copy和文件删除
  12. POJ3208 Apocalypse Someday
  13. Git永久删除文件和历史记录
  14. Auth认证模块
  15. 【转】Redis 总结精讲 看一篇成高手系统-4
  16. 如何解决 yum安装出现This system is not registered with RHN
  17. ubuntu HackRF One相关环境搭建
  18. power designer和uml应用
  19. 转:基于Flume的美团日志收集系统(一)架构和设计
  20. 基于tiny4412的Linux内核移植 -- MMA7660驱动移植(九)

热门文章

  1. 阿里云云服务器测试uwgis的基本流程
  2. (转)Java并发编程:阻塞队列
  3. mysql插入文本文档及读取
  4. 【每日Scrum】第二天冲刺
  5. Codeforces 400C 矩阵乘法 数学规律
  6. 04-for循环的各个语句及list列表学习
  7. tomcat用户配置
  8. vue 动画原理 part1
  9. 十二星座 英文名:Aries 金牛座 (4/21 - 5/20)的英文名: Taurus 双子座 (5/21 - 6/21)的英文名: Gemini 巨蟹座 (6/22 - 7/22)的英文名: Cancer 狮子座 (7/23 - 8/22)的英文名: Leo 处女座/室女座 (8/23 - 9/22)的英文名: Virgo 天秤座 (9/2
  10. Fib数列问题(项数很大)