[LeetCode] Path Sum 二叉树的路径和
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.
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 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
这道题给了一棵二叉树,问是否存在一条从跟结点到叶结点到路径,使得经过到结点值之和为一个给定的 sum 值,这里需要用深度优先算法 DFS 的思想来遍历每一条完整的路径,也就是利用递归不停找子结点的左右子结点,而调用递归函数的参数只有当前结点和 sum 值。首先,如果输入的是一个空结点,则直接返回 false,如果如果输入的只有一个根结点,则比较当前根结点的值和参数 sum 值是否相同,若相同,返回 true,否则 false。 这个条件也是递归的终止条件。下面就要开始递归了,由于函数的返回值是 Ture/False,可以同时两个方向一起递归,中间用或 || 连接,只要有一个是 True,整个结果就是 True。递归左右结点时,这时候的 sum 值应该是原 sum 值减去当前结点的值,参见代码如下:
解法一:
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;
if (!root->left && !root->right && root->val == sum ) return true;
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
我们也可以使用迭代的写法,这里用的也是先序遍历的迭代写法,先序遍历二叉树,左右子结点都需要加上其父结点值,这样当遍历到叶结点时,如果和 sum 相等了,那么就说明一定有一条从 root 过来的路径。注意这里不必一定要先处理右子结点,调换下顺序也是可以的,因为不论是先序遍历的根-左-右,还是根-右-左,并不会影响到找路径,参见代码如下:
解法二:
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;
stack<TreeNode*> st{{root}};
while (!st.empty()) {
TreeNode *t = st.top(); st.pop();
if (!t->left && !t->right) {
if (t->val == sum) return true;
}
if (t->right) {
t->right->val += t->val;
st.push(t->right);
}
if (t->left) {
t->left->val += t->val;
st.push(t->left);
}
}
return false;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/112
类似题目:
Binary Tree Preorder Traversal
参考资料:
https://leetcode.com/problems/path-sum/
https://leetcode.com/problems/path-sum/discuss/36534/My-java-no-recursive-method
https://leetcode.com/problems/path-sum/discuss/36378/AcceptedMy-recursive-solution-in-Java
https://leetcode.com/problems/path-sum/discuss/36382/Accepted-By-using-postorder-traversal
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Path Sum 二叉树的路径和的更多相关文章
- [LeetCode] 112. Path Sum 二叉树的路径和
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
- [leetcode]124. Binary Tree Maximum Path Sum二叉树最大路径和
Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any ...
- LeetCode 112. Path Sum 二叉树的路径和 C++
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...
- LeetCode Binary Tree Maximum Path Sum 二叉树最大路径和(DFS)
题意:给一棵二叉树,要求找出任意两个节点(也可以只是一个点)的最大路径和,至少1个节点,返回路径和.(点权有负的.) 思路:DFS解决,返回值是,经过从某后代节点上来到当前节点且路径和最大的值.要注意 ...
- Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划)
Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划) 题目描述 已知一个正方形二维数组A,我们想找到一条最小下降路径的和 所谓下降路径是指,从一行到 ...
- LeetCode:Path Sum I II
LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...
- 【LeetCode-面试算法经典-Java实现】【064-Minimum Path Sum(最小路径和)】
[064-Minimum Path Sum(最小路径和)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a m x n grid filled with ...
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] 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 ...
随机推荐
- 微信小程序基础入门
准备 Demo 项目地址 https://github.com/zce/weapp-demo Clone or Download(需准备GIT环境) $ cd path/to/project/root ...
- angularjs和ajax的结合使用 (一)
好久没写文了.这是一篇关于easyui配合ajax使用 的文章, 顺带介绍angularjs的使用 以及让你感受到angularjs的威力.网上对于ajax 的文也是多如牛毛 .我就不直接 从那种原生 ...
- 基于STM32Cube的脉冲输出
方法一:定时器定时I/O反转生成脉冲波形 1.建立STM32Cube选择STM32F429,我使用的STM32F429-discovery开发板,晶振是8MHz,时钟配置为180M,这样定时器内部时钟 ...
- C#开发微信门户及应用(20)-微信企业号的菜单管理
前面几篇陆续介绍了很多微信企业号的相关操作,企业号和公众号一样都可以自定义菜单,因此他们也可以通过API进行菜单的创建.获取列表.删除的操作,因此本篇继续探讨这个主体,介绍企业号的菜单管理操作. 菜单 ...
- 1、Python基本概念
1.数 python中有4种类型的数--整数.长整数.浮点数和复数 2.字符串 单引号.双引号或者三引号包含的字符序列,如: 'char' #单引号 "char" #双引号 ''' ...
- GJM: 设计模式 - 观察者模式
GJM : 观察者模式 视频地址: http://www.imooc.com/learn/415 本课程通过一个天气预报的发布和订阅案例,来讲解观察者模式在Java项目中的应用.主要包括观察者模式的结 ...
- jQ图片列表光标移动动画
本效果使用jQuery和CSS实现了图片列表,当鼠标移入时图片向左微动,移出则复原. 效果展示: http://hovertree.com/texiao/jquery/88/ 效果图如下: 其中的jQ ...
- Android简单介绍SharedPreference,内部文件,sdcard数据存储
SharedPreference 以xml的结构储存简单的数据,储存在data/data/程序包名/shared_prefs文件夹中 使用方式 创建对象的方式有三种 Context 的 getShar ...
- iOS报错[__NSCFNumber length]: unrecognized
出现这种报错很大的原因是因为类型给错了,或许你这个数据是从json上解析后得到的,但是需要看一下这个数据是NSString还是NSNumber类型,如果是NSNumber类型的话,你又直接使用NSSt ...
- CALayer的transform属性
先来与View比较一下 View:transform -> CGAffineTransformRotate... layer:transform -> CATransform3DRotat ...