[LC] 113. Path Sum II
2024-08-29 11:53:22
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()
最新文章
- jquery 购物车飞入效果
- JMS
- php 读取网页源码 , 导出成txt文件, 读取xls,读取文件夹下的所有文件的文件名
- jquery工具方法proxy
- SVM 最大间隔目标优化函数(NG课件2)
- django模型
- \n 与 \r
- UltraEdit-32 恢复到初始默认配置
- WCF技术剖析之二十七: 如何将一个服务发布成WSDL[编程篇]
- Entity Framework Core 2.0 数据库迁移
- C# 文件copy和文件删除
- POJ3208 Apocalypse Someday
- Git永久删除文件和历史记录
- Auth认证模块
- 【转】Redis 总结精讲 看一篇成高手系统-4
- 如何解决 yum安装出现This system is not registered with RHN
- ubuntu HackRF One相关环境搭建
- power designer和uml应用
- 转:基于Flume的美团日志收集系统(一)架构和设计
- 基于tiny4412的Linux内核移植 -- MMA7660驱动移植(九)
热门文章
- 阿里云云服务器测试uwgis的基本流程
- (转)Java并发编程:阻塞队列
- mysql插入文本文档及读取
- 【每日Scrum】第二天冲刺
- Codeforces 400C 矩阵乘法 数学规律
- 04-for循环的各个语句及list列表学习
- tomcat用户配置
- vue 动画原理 part1
- 十二星座 英文名: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
- Fib数列问题(项数很大)