My C++ solution using an auxiliary routine (recursion)


  • 0
    L
    class Solution {
    public:
        void hasPathSum(TreeNode* root, int sum, int currentSum, bool& result) {
            currentSum += root->val;
            
            bool isLeaf = root->left == NULL && root->right == NULL;
            if (currentSum == sum && isLeaf)
                result = true;
            
            if (root->left != NULL)
                hasPathSum(root->left, sum, currentSum, result);
            if (root->right != NULL)
                hasPathSum(root->right, sum, currentSum, result);
        }
    
        bool hasPathSum(TreeNode* root, int sum) {
            if (root == NULL)
                return false;
            
            bool result = false;
            int currentSum = 0;
            hasPathSum(root, sum, currentSum, result);
            return result;
        }
    };

Log in to reply
 

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