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. Sitecore 8.2 渠道简介

    渠道是联系人通过广告系列或面对面与您的品牌互动时所使用的路径.联系人可以通过手机上的应用与您的品牌互动,点击社交网络上的广告访问您的网站,或访问实体店购买商品.使用Sitecore体验平台,您可以使用 ...

  2. Spring Cloud Ribbon客户端负载均衡(四)

    序言 Ribbon 是一个客户端负载均衡器(Nginx 为服务端负载均衡),它赋予了应用一些支配 HTTP 与 TCP 行为的能力,可以得知,这里的客户端负载均衡也是进程内负载均衡的一种.它在 Spr ...

  3. 『CSP2019-S 第二轮退役记』

    Day0 到杭州的时候是下午,休息了一下就吃完饭了. 晚上的时候闲着没事复习了一下几个不太熟的数论板子,\(\mathrm{exgcd}\),\(\mathrm{ExCRT}\),\(\mathrm{ ...

  4. sqlserver the name is not a valid identifier error in function

    参考资料:https://stackoverflow.com/questions/22008859/the-name-is-not-a-valid-identifier-error-in-functi ...

  5. AD的故事继续在Sharepoint里续演

    本以为AD的开发深入工作,可能暂时先放放了,这不最近又一次接触了SP的知识领域,又一次见到了久违相识的老朋友AD域控了,让我没有想到其实服务器这块儿微软的份额这么大...不得不深思微软的核心业务是啥, ...

  6. CSS自定义右键菜单

    <style> .menu { width: 100px; font-size: 14px; font-family: "微软雅黑"; border: 1px soli ...

  7. 「白帽挖洞技能提升」ThinkPHP5 远程代码执行漏洞-动态分析

    ThinkPHP是为了简化企业级应用开发和敏捷WEB应用开发而诞生的,在保持出色的性能和至简代码的同时,也注重易用性.但是简洁易操作也会出现漏洞,之前ThinkPHP官方修复了一个严重的远程代码执行漏 ...

  8. Kail Linux xface 2019.2

    概述: -OS: Kali-Rolling (2019.2) -DE: XFCE -WM: Arc-Dark -WM Theme: Arc-Dark -Icons: Korla -Term Font: ...

  9. 【转】gradle for android 第一篇

    正如大家所见,这是本英文书,而由于国内的gradle翻译资料不全,所以特次开辟专栏,翻译gradle for android这本书,同时添加自己的心得体会以及在实际工作上的实战,希望大家能够喜欢. 如 ...

  10. X264-编码模块和NAL打包输出

    在上一篇介绍了编码器的VCL编码操作,分析了函数x264_slice_write().函数x264_slice_write()里有四个关键模块,分别是宏块分析模块.宏块编码模块.熵编码模块和滤波模块, ...