作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/


题目地址:https://leetcode.com/problems/path-sum-ii/description/

题目描述

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]
]

题目大意

在一棵二叉树中,找出从根节点到叶子节点的和为target的所有路径。

解题方法

二叉树问题大多都可以用递归和迭代的方法求解。本题也是如此。

左边是BFS,按照层进行搜索;图右边是DFS,先一路走到底,然后再回头搜索。

BFS

BFS使用队列,把每个还没有搜索到的点依次放入队列,然后再弹出队列的头部元素当做当前遍历点。BFS总共有两个模板:

  1. 如果不需要确定当前遍历到了哪一层,BFS模板如下。
while queue 不空:
cur = queue.pop()
if cur 有效且未被访问过:
进行处理
for 节点 in cur 的所有相邻节点:
if 该节点有效:
queue.push(该节点)
  1. 如果要确定当前遍历到了哪一层,BFS模板如下。
    这里增加了level表示当前遍历到二叉树中的哪一层了,也可以理解为在一个图中,现在已经走了多少步了。size表示在当前遍历层有多少个元素,也就是队列中的元素数,我们把这些元素一次性遍历完,即把当前层的所有元素都向外走了一步。
level = 0
while queue 不空:
size = queue.size()
while (size --) {
cur = queue.pop()
if cur 有效且未被访问过:
进行处理
for 节点 in cur的所有相邻节点:
if 该节点有效:
queue.push(该节点)
}
level ++;

上面两个是通用模板,在任何题目中都可以用,是要记住的!

本题要求所有的路径,不需要按层遍历,因此使用模板一。(注:模板二的使用见102. 二叉树的层序遍历

代码如下,使用队列,同时保存(将要处理的节点,路径,路径和),这样在访问一个节点的时候,就能知道已有的路径和「路径和」。如果当前节点是叶子节点并且,已有的「路径和」加上当前叶子的值等于sum,说明找到了一条满足题意的路径,放入结果 res 中。

# 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 = []
que = deque()
que.append((root, [], 0)) # 将要处理的节点,路径,路径和
while que:
node, path, pathSum = que.popleft()
if not node: # 如果是空节点,不处理
continue
if not node.left and not node.right: # 如果是叶子节点
if node.val + pathSum == sum: # 加上叶子节点后,路径和等于sum
res.append(path + [node.val]) # 保存路径
# 处理左子树
que.append((node.left, path + [node.val], pathSum + node.val))
# 处理右子树
que.append((node.right, path + [node.val], pathSum + node.val))
return res

DFS

题目要求二叉树中从根节点到叶子节点的「路径和」为 sum 的所有路径。

我们必须使用一个变量 res 保存最终的所有路径结果,用一个变量 path 保存每条路径。另外需要记录路径和,我们反其道而行之,记录到达每个节点时的sum - 「路径和」;如果遍历到叶子节点的时候,sum - 「路径和」 恰好等于叶子节点的值,那么这条从根节点到叶子节点的路径即为一条满足题目的路径。

在下面的代码中,res 变量从头到尾只有同一个,但是每次调用 dfs() 函数的时候 path 变量都是不同的。Python 中,path + [root.val] 会生成一个新的列表,因此所有的递归函数的里面的 path 操作不会互相干扰。

# 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 = []
self.dfs(root, sum, res, [])
return res def dfs(self, root, sum, res, path):
if not root: # 空节点,不做处理
return
if not root.left and not root.right: # 叶子节点
if sum == root.val: # 剩余的「路径和」恰好等于叶子节点值
res.append(path + [root.val]) # 把该路径放入结果中
self.dfs(root.left, sum - root.val, res, path + [root.val]) # 左子树
self.dfs(root.right, sum - root.val, res, path + [root.val]) # 右子树

日期

2018 年 6 月 22 日 ———— 这周的糟心事终于完了

【LeetCode】113. Path Sum II 路径总和 II 解题报告(Python)的更多相关文章

  1. [LeetCode] 113. Path Sum II 路径和 II

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

  2. [LeetCode] 437. Path Sum III 路径和 III

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  3. 【LeetCode】129. Sum Root to Leaf Numbers 解题报告(Python)

    [LeetCode]129. Sum Root to Leaf Numbers 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/pr ...

  4. LeetCode 113. Path Sum II路径总和 II (C++)

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

  5. [LeetCode] 113. Path Sum II ☆☆☆(二叉树所有路径和等于给定的数)

    LeetCode 二叉树路径问题 Path SUM(①②③)总结 Path Sum II leetcode java 描述 Given a binary tree and a sum, find al ...

  6. 113 Path Sum II 路径总和 II

    给定一个二叉树和一个和,找到所有从根到叶路径总和等于给定总和的路径.例如,给定下面的二叉树和 sum = 22,              5             / \            4 ...

  7. [LeetCode] 113. Path Sum II 二叉树路径之和之二

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

  8. leetcode 113. Path Sum II (路径和) 解题思路和方法

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

  9. [leetcode] 113. Path Sum II (Medium)

    原题链接 子母题 112 Path Sum 跟112多了一点就是保存路径 依然用dfs,多了两个vector保存路径 Runtime: 16 ms, faster than 16.09% of C++ ...

随机推荐

  1. SpringBoot 整合 MyBatis,实现 CRUD 示例

    目录 前言 创建项目/模块 SpringBoot Console Application CommandLineRunner SpringBoot 集成 MyBatis 创建数据库/表 配置数据源/连 ...

  2. C#数字验证

    using System; using System.Collections; using System.Configuration; using System.Data; using System. ...

  3. C语言中的指针与整数相加的值计算

    以下分三种情况: 1. 指针 + 整数值 2. 整数 + 整数  3. 指针强制转换为另一个类型后(指针或者是整数)  +  整数 测试例子: 1 struct AAA{ int a; char b[ ...

  4. A Child's History of England.7

    After the death of Ethelbert, Edwin, King of Northumbria [公元616年,隋朝末年], who was such a good king tha ...

  5. 大数据学习day26----hive01----1hive的简介 2 hive的安装(hive的两种连接方式,后台启动,标准输出,错误输出)3. 数据库的基本操作 4. 建表(内部表和外部表的创建以及应用场景,数据导入,学生、分数sql练习)5.分区表 6加载数据的方式

    1. hive的简介(具体见文档) Hive是分析处理结构化数据的工具   本质:将hive sql转化成MapReduce程序或者spark程序 Hive处理的数据一般存储在HDFS上,其分析数据底 ...

  6. Linux基础命令---mysqldump数据库备份

    mysqldump mysqldump是一个客户端的备份程序,他可以备份数据库,或者将数据库传输到另外一个服务器. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora. ...

  7. python做一个http接口测试框架

    目录结构 project case#测试用例 suite#测试目录 logs#测试日志 papi#测试类 result#测试结果 setting.py#配置文件 1.日志类,用于测试时日志记录 pya ...

  8. OC-封装,继承,多态

    主要内容概括 标号 主题 内容 一 封装 面向对象三大特性;封装的概念/原因/好处/原则 二 *getter和setter setter / getter方法;注意点 三 自定义代码段 如何自定义代码 ...

  9. MySQL 迁移到 Redis 记

    前些日子,一个悠闲又不悠闲的下午,我还在用 Node.js 写着某个移动互联网应用的 API 服务端.那时还是用 MySQL 作为数据库,一切都很好,所有功能正常运行.可是有很多问题让人不安: 频繁的 ...

  10. virtualBox 系统移植

    把virtualbox已经存在的系统移植到其他机器. 1.把系统如下文件考到一个安装了virtualbox的机器. 2.点击控制-->注册 然后浏览到复制的文件路径. 3.修改uuid 不管是l ...