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

类似题目:

Path Sum IV

Path Sum III

Binary Tree Maximum Path Sum

Path Sum II

Sum Root to Leaf Numbers

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] 112. Path Sum 二叉树的路径和的更多相关文章

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

  2. [LeetCode] 112. Path Sum ☆(二叉树是否有一条路径的sum等于给定的数)

    Path Sum leetcode java 描述 Given a binary tree and a sum, determine if the tree has a root-to-leaf pa ...

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

  4. leetcode 112. Path Sum 、 113. Path Sum II 、437. Path Sum III

    112. Path Sum 自己的一个错误写法: class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(root ...

  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. (二叉树 DFS 递归) 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 ...

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

  8. 112. Path Sum二叉树路径和

    [抄题]: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding ...

  9. LeetCode 437. Path Sum III (路径之和之三)

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

随机推荐

  1. Django学习笔记(11)——开发图书管理页面

    一,项目题目: 开发图书管理页面 该项目主要练习Django对多个数据库进行增删改查的操作. 二,项目需求: 基础需求:75% 1. 列出图书列表.出版社列表.作者列表 2. 点击作者,会列出其出版的 ...

  2. 正式开放 | 阿里云 10 亿级镜像服务正式支持 Helm Charts,云原生交付再加速!

    作者 | 阿里巴巴高级开发工程师 谢于宁(予栖) 2018 年 6 月,Helm 正式加入了 CNCF 孵化项目: 2018 年 8 月,据 CNCF 的调研表明,有百分之六十八的开发者选择了 Hel ...

  3. JVM的监控工具之jstack

    参考博客:https://www.jianshu.com/p/213710fb9e40 jstack(Stack Trace for Java)命令用于生成虚拟机当前时刻的线程快照(一般称为threa ...

  4. Zabbix 设置自动添加主机两种方法(自动注册、自动发现)

    在实际生产环境中,我们可能需要将很多台主机添加到 Zabbix Server 里,我们进行手动添加的话,会比较麻烦.费时,而且还容易出错.所以一般我们会设置主机自动注册.这样就比较方便. 官方文档链接 ...

  5. Mysql综述--数据是如何读存的?(2)

    页的结构 页是一种InnoDB管理存储空间的基本单位,它一般大小在16kb左右.实际上存在着许多不同类型的页,我们这次主要介绍的页是用来存储数据的,也叫做索引页. 接下来看看索引页的结构图: 比较重要 ...

  6. jmeter实操及性能测试基础知识整理 - 不断更新

    主要基于jmetet工具 有任何疑问直接留言,可以相互讨论 线程组菜单: 线程数:并发数量Rame-Up时间(秒):多久跑完线程数,比如线程是10,Rame-Up时间是10秒,就是10秒内跑完10个线 ...

  7. WinRAR命令行版本 rar.exe使用详解(适用Linux)

    RAR 命令行语法: RAR.exe <命令> [ -<开关> ] <压缩文件> [ <@列表文件...> ] [ <文件...> ] [ ...

  8. Git内部原理浅析

    Git独特之处 Git是一个分布式版本控制系统,首先分布式意味着Git不仅仅在服务端有远程仓库,同时会在本地也保留一个完整的本地仓库(.git/文件夹),这种分布式让Git拥有下面几个特点: 1.直接 ...

  9. 将流数据输出到Mysql中

    outputMysqlApp.scala import java.sql.DriverManager import org.apache.spark.SparkConf import org.apac ...

  10. 【原创】CentOS 7 安装redis 5

    1.下载redis安装包 cd /softwares/ wget http://download.redis.io/releases/redis-5.0.5.tar.gz 2.解压redis-5.0. ...