9 ms C++ with recursion


  • 0
    F

    void pathsum(TreeNode* root,int result,int sum,bool& res){
    if(!root->left && !root->right){
    if(result == sum) res = true;
    return;
    }
    if(root->left){
    pathsum(root->left,result+root->left->val,sum,res);
    }
    if(root->right){
    pathsum(root->right,result+root->right->val,sum,res);
    }
    }
    bool hasPathSum(TreeNode* root, int sum) {
    int result = 0;
    bool res = false;
    if(!root) return false;
    pathsum(root,root->val,sum,res);
    return res;
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.