[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 ...
随机推荐
- java对接微信支付
对接微信扫码支付(模式2),前端使用velocity技术 (1)调用微信支付接口(view层) 此部分业务逻辑部分可以省略 @RequestMapping("/wxpay.htm" ...
- (转)Updates were rejected because the tip of your current branch is behind
刚创建的github版本库,在push代码时出错: $ git push -u origin masterTo git@github.com:******/Demo.git ! [rejected] ...
- ctf题目writeup(3)
题目地址: https://www.ichunqiu.com/battalion 1. 这个是个mp3,给的校验是为了下载下来的. 下来之后丢进audicity中 放大后根据那个音块的宽度来确定是 . ...
- POJ3177 边双连通分量
Redundant Paths Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 18580 Accepted: 7711 ...
- Python3 函数参数
# # 常规参数 # def jiafa(a,b): # print(a+b) # # jiafa(5,6) # # # def xinxi(name,location,sex='male'): # ...
- (数据科学学习手札20)主成分分析原理推导&Python自编函数实现
主成分分析(principal component analysis,简称PCA)是一种经典且简单的机器学习算法,其主要目的是用较少的变量去解释原来资料中的大部分变异,期望能将现有的众多相关性很高的变 ...
- 实现一个带有指纹加密功能的笔记本(Android)第一部分
自己经常会忘记一些密码什么的,想把这些密码保存下来,但是别人做的软件总有一点不安全的感觉,所以自己动手做了一个带有指纹加密的笔记本. 以下是本工程用到的一些第三方包 compile 'org.gree ...
- LeetCode题目解答
LeetCode题目解答——Easy部分 Posted on 2014 年 11 月 3 日 by 四火 [Updated on 9/22/2017] 如今回头看来,里面很多做法都不是最佳的,有的从复 ...
- error C2248: 'QObject::QObject' : cannot access private member declared in class 'QObject'
1.error C2471: cannot update program database vc90.pdb 解决方案:https://blog.csdn.net/shuixin536/article ...
- 『Golang』MongoDB在Golang中的使用(mgo包)
有关在Golang中使用mho进行MongoDB操作的最简单的例子.