LeetCode:Path Sum

Path Sum

Total Accepted: 78908 Total Submissions: 261199 Difficulty: Easy

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.























code:

/**
 * 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(NULL == root) return false;
        if(sum==root->val && NULL == root->left && NULL == root->right) return true;
        return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
    }
};


阅读更多
版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/itismelzp/article/details/49949803
个人分类: LeetCode OJ
所属专栏: LeetCode解题记录
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode:Path Sum

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭