C recursive solution


  • 0
    B
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    bool hasPathSum(struct TreeNode* root, int sum) {
        bool isPathSum = false;
        int isSum = 0;
        
        if(root == NULL) return false;
        
        isSum += root->val;
        
        if((isSum == sum) && (root->left == NULL) && (root->right == NULL))
        {
            isPathSum = true;
        }
        else
        {
            isPathSum ^= hasPathSum(root->left, (sum-root->val)) || hasPathSum(root->right, (sum-root->val));
        }
        
        return isPathSum;
    }
    

Log in to reply
 

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