112. Path Sum


1. 问题描述

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

Tags: Tree Depth-first Search

Similar Problems: (M) Path Sum II (H) Binary Tree Maximum Path Sum (M) Sum Root to Leaf Numbers

2. 解题思路
3. 代码

/**
 * Definition for a binary tree node.
 * 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)
        {
            return false;
        }
        if (root->left == NULL && root->right == NULL && root->val == sum)
        {
            return true;
        }
        else
        {
            return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
        }
    }
};

4. 反思

优质内容筛选与推荐>>
1、vSphere Replication:虚拟机的保护伞
2、Task15 节点层次笔记
3、关于百万用户服务器架构能力(一)QQ游戏服务器架构
4、【未完】训练赛20190304:KMP+树状数组+线段树+优先队列
5、C++ 11学习和掌握 ——《深入理解C++ 11:C++11新特性解析和应用》读书笔记(一)


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn