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路径和的更多相关文章

  1. [leetcode] Path sum路径之和

    要求给定树,与路径和,判断是否存在从跟到叶子之和为给定值的路径.比如下图中,给定路径之和为22,存在路径<5,4,11,2>,因此返回true;否则返回false. 5 / \ 4 8 / ...

  2. 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 ...

  3. [LeetCode] Path Sum III 二叉树的路径和之三

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

  4. [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 ...

  5. [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 ...

  6. [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 ...

  7. [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 ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. Redis面试问题

    下面列出的这些其中有一些是我面试时遇到的,但是当时自己还不会,所以在网站上找了以下,然后整理出来,加强记忆 感谢码洞将这些问题整理出来: Redis有哪些数据结构? 字符串String.字典Hash. ...

  2. php 电商系统SKU库存设计

    sku 全称为:Stock Keeping Unit,是库存进出计量的基本单元. 我们一般会在电商网站基本都会看到 比如淘宝,JD 淘宝和JD的 方式可能不一样,因为我不清楚他们具体是如何设计的, J ...

  3. Python实现多属性排序

    Python实现多属性排序 多属性排序:假如某对象有n个属性,那么先按某规则对属性a进行排序,在属性a相等的情况下再按某规则对属性b进行排序,以此类推. 现有对象Student: class Stud ...

  4. LeetCode 二叉树的层次遍历 C++

    给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如:给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其层 ...

  5. Python标准库--inspect

    inspect模块是针对模块,类,方法,功能等对象提供些有用的方法.例如可以帮助我们检查类的内容,检查方法的代码,提取和格式化方法的参数等. import inspect import os clas ...

  6. Log4net 根据日志类别保存到不同的文件,并按照日期生成不同文件名称

    <configuration> <configSections> <!--日志记录--> <section name="log4net" ...

  7. 基于jersey和Apache Tomcat构建Restful Web服务(一)

    基于jersey和Apache Tomcat构建Restful Web服务(一) 现如今,RESTful架构已然成为了最流行的一种互联网软件架构,它结构清晰.符合标准.易于理解.扩展方便,所以得到越来 ...

  8. Qt BarChart实践

    按照帮助文档编写 运行截图 上代码 #include "widget.h" #include "ui_widget.h" Widget::Widget(QWid ...

  9. Qt irrlicht(鬼火)3D引擎 摄像机旋转问题

    点击打开链接Irrlicht中的摄像有一个函数 setUpVector() if (m_device != 0 ) { core::vector3df rotation(y,x,0.f); m_cam ...

  10. FetchType.LAZY 时属性加上@JsonIgnore,避免返回时报错:Could not write JSON: failed to lazily initialize a collection of role

    [示例] @OneToMany(fetch=FetchType.LAZY) @JsonIgnore @Fetch(FetchMode.SELECT) @Cascade(value={CascadeTy ...