[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.
For example:
Given the below binary tree andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
题意:给定一个数,判断是否存在一条从根节点到叶节点的路径,使得,路径上节点所对应的值得和等于这个数。
方法一:使用递归解法。
针对一条路径:通过用sum减去当前节点的值,直到最后看最后叶节点的值是否等于sum剩余的值来判断是否存在。
一、终止条件,1)初始时,root为空,返回false;最后,root->left、root->right不存在时,依旧不等于sum,也返回false;
2)当达到叶节点时,当前节点的值等于sum剩余值,返回true;
二、递归表达式,对一个节点,左、右子树中有一条路径满足条件就行。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum)
{
if(root==NULL) return false; if(root->left==NULL&&root->right==NULL&&root->val==sum)
return true; return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val) ;
}
};
方法二:利用后续遍历的思想
减值的过程类似后续遍历中的方法二。具体过程:先沿左子树的左孩子不停的将左孩子重复入栈,并计算和栈中节点的和,直到左孩子为空,若为叶节点且val=sum,则返回true,否则再转向右孩子。定义变量pre防止重复的访问右子树,每次出栈时,特别要注意的是,要将cur赋值为NULL这样可以跳过while循环,避免重复访问左孩子。具体代码如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum)
{
stack<TreeNode *> stk;
TreeNode *pre=NULL;
TreeNode *cur=root;
int temVal=; while(cur|| !stk.empty())
{
while(cur)
{
stk.push(cur);
temVal+=cur->val;
cur=cur->left;
}
cur=stk.top();
if(cur->left==NULL&&cur->right==NULL&&temVal==sum)
return true;
if(cur->right&&cur->right !=pre)
cur=cur->right;
else
{
stk.pop();
temVal-=cur->val;
pre=cur;
cur=NULL;
} }
return false;
}
};
[Leetcode] Path Sum路径和的更多相关文章
- [leetcode] Path sum路径之和
要求给定树,与路径和,判断是否存在从跟到叶子之和为给定值的路径.比如下图中,给定路径之和为22,存在路径<5,4,11,2>,因此返回true;否则返回false. 5 / \ 4 8 / ...
- 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] 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 ...
- [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 ...
- [LeetCode] Path Sum IV 二叉树的路径和之四
If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digit ...
- [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] 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 ...
- [leetcode]Path Sum II
Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals ...
随机推荐
- 如何改变memcached默认的缓存时间?
我们在使用php的memcached的扩展来对memcached进行数据添加时,数据的有效时间有两种方式.如下图. 至于设置一个UNIX时间戳或 以秒为单位的整数(从当前算起的时间差)来说明 ...
- ECSHOP和SHOPEX快递单号查询申通插件V8.6专版
发布ECSHOP说明: ECSHOP快递物流单号查询插件特色 本ECSHOP快递物流单号跟踪插件提供国内外近2000家快递物流订单单号查询服务例如申通快递.顺丰快递.圆通快递.EMS快递.汇通快递.宅 ...
- Excel VBA表格自行开发计划
Excel VBA表格自行开发计划 要求功能 1. 批量删除 2. [X] 批量填充 3. [X] 批量重命名 4. [ ] 按颜色求和 5. [ ] 按底纹色选中单元格 6. [ ] 统计底纹颜色个 ...
- python3 练习题100例 (十一)
题目十一:举例证明角谷猜想:以一个正整数N为例,如果N为偶数,就将它变为N/2,如果除后变为奇数,则将它乘3加1(即3N+1).不断重复这样的运算,经过有限步后,一定可以得到1. #!/usr/bin ...
- Vue简单使用,
一些零碎的知识点: 在js中变量的声明 有三种方式: let,var, const let: 对应的是一个块级作用域 { let a = 12 } console.log(a) 这是未声明的, var ...
- R语言学习笔记(十六):构建分割点函数
选取预测概率的分割点 cutoff<- function(n,p){ pp<-1 i<-0 while (pp>=0.02) { model.predfu<-rep(&q ...
- delphi 数据库中Connection与Query连接数量问题思考
今天闲着没事,测试了一下Connection连接MSSQL,可以承受多少连接. 1.看看ADOConnection的连接数:写了一个代码,动态创建,测试了10000个连接,花了大约5~10分钟创 ...
- linux redhat 打开防火墙中的某个端口
服务器成功监听了一个端口(如 5500),但是外面连接不进来,telnet其端口不通,解决办法如下(在root用户下): $ /sbin/iptables -I INPUT -p tcp --dpor ...
- 深入理解计算机系统(1)--hello world程序的生命周期
第一篇笔记的主题是讨论Hello World程序的生命周期,程序是最简单的hello world程序,使用高级C语言编写. 先介绍整个生命周期中涉及到的几个部分以及相应的概念,然后总结整个生命周期,最 ...
- mysql 处理日期格式
DATE_FORMAT(createTime,'%Y-%m-%d %H:%i:%s') 对应格式: 2018-12-17 17:33:43 DATE_FORMAT()函数所有格式: 以后有需要在自 ...