【LeetCode】112. 路径总和 Path Sum 解题报告(Java & Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/path-sum/#/description
题目描述
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
题目大意
从根节点到叶子节点是否存在一条路径,它的所有节点的和等于target.
解题方法
DFS
这个题要背下来!!
首先是 DFS 解法,该解法的想法是一直向下找到叶子节点,如果到叶子节点时sum == 0
,说明找到了一条符合要求的路径。
我自己第一遍做的时候犯了一个错误,把递归函数写成了下面的解法:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return sum == 0
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
这种代码的错误在,没有判断 root 是否为叶子节点。比如 root 为空的话,题目的意思是要返回 False 的,而上面的代码会返回 sum == 0。又比如,对于测试用例 树为[1,2]
, sum = 0 时,上面的结果也会返回为 True,因为对于上述代码,只要左右任意一个孩子的为空时 sum == 0 就返回 True 。
当题目中提到了叶子节点时,正确的做法一定要同时判断节点的左右子树同时为空才是叶子节点。
Python 代码如下:
# 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 hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root: return False
if not root.left and not root.right:
return sum == root.val
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
Java 代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null){
return false;
}
if(root.left == null && root.right == null){
return root.val == sum;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
回溯
这里的回溯指 利用 DFS 找出从根节点到叶子节点的所有路径,只要有任意一条路径的 和 等于 sum,就返回 True。
下面的代码并非是严格意义上的回溯法,因为没有重复利用 path 变量。
Python 代码如下:
# 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 hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root: return False
res = []
return self.dfs(root, sum, res, [root.val])
def dfs(self, root, target, res, path):
if not root: return False
if sum(path) == target and not root.left and not root.right:
return True
left_flag, right_flag = False, False
if root.left:
left_flag = self.dfs(root.left, target, res, path + [root.left.val])
if root.right:
right_flag = self.dfs(root.right, target, res, path + [root.right.val])
return left_flag or right_flag
BFS
BFS 使用 队列 保存遍历到每个节点时的路径和,如果该节点恰好是叶子节点,并且 路径和 正好等于 sum,说明找到了解。
Python 代码如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
que = collections.deque()
que.append((root, root.val))
while que:
node, path = que.popleft()
if not node.left and not node.right and path == sum:
return True
if node.left:
que.append((node.left, path + node.left.val))
if node.right:
que.append((node.right, path + node.right.val))
return False
栈
除了上面的 队列 解法以外,也可以使用 栈,同时保存节点和到这个节点的路径和。但是这个解法已经不是 BFS。因为会优先访问 后进来 的节点,导致会把根节点的右子树访问结束之后,才访问左子树。
可能会有朋友好奇很少见到这种写法,为什么代码可行?答案是:栈中同时保存了 (节点,路径和)
,也就是说只要能把所有的节点访问一遍,那么就一定能找到正确的结果。无论是用 队列 还是 栈,都是一种 树的遍历 方式,只不过访问顺序有所有不同罢了。
Python 代码如下:
# 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 hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
stack = []
stack.append((root, root.val))
while stack:
node, path = stack.pop()
if not node.left and not node.right and path == sum:
return True
if node.left:
stack.append((node.left, path + node.left.val))
if node.right:
stack.append((node.right, path + node.right.val))
return False
日期
2017 年 5 月 12 日
2018 年 6 月 22 日
2018 年 11 月 24 日 —— 周六快乐
2020 年 7 月 7 日 —— 昨日 A 股涨了5.7%,5 年来的最高单日涨幅
【LeetCode】112. 路径总和 Path Sum 解题报告(Java & Python)的更多相关文章
- LeetCode 112. 路径总和(Path Sum) 10
112. 路径总和 112. Path Sum 题目描述 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和. 说明: 叶子节点是指没有子节点的节 ...
- 【LeetCode】64. Minimum Path Sum 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- LeetCode: Binary Tree Maximum Path Sum 解题报告
Binary Tree Maximum Path SumGiven a binary tree, find the maximum path sum. The path may start and e ...
- 【LeetCode】931. Minimum Falling Path Sum 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 相似题目 参考资料 日期 题目地址:htt ...
- 【LeetCode】459. Repeated Substring Pattern 解题报告(Java & Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历子串 日期 [LeetCode] 题目地址:ht ...
- 【LeetCode】743. Network Delay Time 解题报告(Python)
[LeetCode]743. Network Delay Time 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: ht ...
- 【LeetCode】486. Predict the Winner 解题报告(Python)
[LeetCode]486. Predict the Winner 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: ht ...
- 【LeetCode】652. Find Duplicate Subtrees 解题报告(Python)
[LeetCode]652. Find Duplicate Subtrees 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博 ...
- 【LeetCode】227. Basic Calculator II 解题报告(Python)
[LeetCode]227. Basic Calculator II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...
随机推荐
- EXCEL-批量下拉填充
3.批量下拉填充 => 全选->Ctrl+G定位空值->随意找一个空白单元格输入=还有此单元格想要填充的内容->按Ctrl+Enter,等待几秒,即可,批量下拉填充:
- Oracle-SQL语句的语法顺序和执行顺序
SQL语句的语法顺序和执行顺序了,我们常见的SQL语法顺序如下: SELECT DISTINCT <Top Num> <select list>FROM [left_table ...
- 简单mvc框架核心笔记
简单mvc框架核心笔记 看了thinkphp5的源码,模仿写了一个简单的框架,有一些心得笔记,记录一下 1.目录结构 比较简单,没有tp那么复杂,只是把需要的核心类写了一些. 核心类库放在mykj里, ...
- ProxyApi-大数据采集用的IP代理池
用于大数据采集用的代理池 在数据采集的过程中,最需要的就是一直变化的代理ip. 自建adsl为问题是只有一个区域的IP. 买的代理存在的问题是不稳定,影响采集效率. 云vps不允许安装花生壳等,即使有 ...
- Spring DAO
Spring DAO 连接池 使用JDBC访问数据库是,频繁的打开连接和关闭连接,造成性能影响,所以有了连接池.数据库连接池负责分配.管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接, ...
- Angular Service设计理念及使用
官方认为组件不应该直接获取或保存数据, 它们应该聚焦于展示数据,而把数据访问的职责委托给某个服务. 而服务就充当着数据访问,逻辑处理的功能.把组件和服务区分开,以提高模块性和复用性. 1.依赖注入 注 ...
- VIM多标签页
:tabnew 增加一个标签 :tabc 关闭当前的tab :tabo 关闭所有其他的tab :tabp 或gT 前一个 :tabn 或gt 后一个 :tabs 显示 ...
- @Transactional注解详细使用
一.@Transactional 注解使用 @Transactional 注解只能用在public 方法上,如果用在protected或者private的方法上,不会报错,但是该注解不会生效. @T ...
- 关于ssh-keygen 生成的key以“BEGIN OPENSSH PRIVATE KEY”开头
现在使用命令 ssh-keygen -t rsa 生成ssh,默认是以新的格式生成,id_rsa的第一行变成了"BEGIN OPENSSH PRIVATE KEY" 而不在是&q ...
- linux系统下命令的学习
本博客是本人工作时做的笔记 ps aux |grep ^profile |grep A190200024 ^ 表示行首匹配 linux查看文件大小: 具体可查看:https://www.cnblogs ...