Path Sum

作者: 日光降临 | 来源:发表于2019-02-24 15:07 被阅读0次
    1. Path Sum
      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.
      Runtime: 16 ms, faster than 20.27% of C online submissions for Path Sum.
      Memory Usage: 19.2 MB, less than 17.86% of C online submissions for Path Sum.
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

bool helper(struct TreeNode* root, int sum,int calc){
    if(root==NULL)
        return 0;
    calc+=root->val;
    if(root->left==NULL && root->right==NULL)
        if(calc==sum)
            return 1;
    return helper(root->left,sum,calc) || helper(root->right,sum,calc);
}
bool hasPathSum(struct TreeNode* root, int sum) {
    int calc = 0;
    return helper(root,sum,calc);
}

相关文章

网友评论

      本文标题:Path Sum

      本文链接:https://www.haomeiwen.com/subject/rzxbyqtx.html