DFS: verbose c++


  • 0
    B
        bool dfs(TreeNode* root, int cursum, int sum)
        {
            if (root==NULL) return false;  //never gets here
            cursum += root->val;
            //if (cursum > sum) return false;  //use if negative values are not allowed
            if (cursum == sum && !root->left && !root->right) return true;
            if (root->left) if (dfs(root->left, cursum, sum)) return true;
            if (root->right) if (dfs(root->right, cursum, sum)) return true;
            return false;
    
        }
        bool hasPathSum(TreeNode* root, int sum) {
            return dfs(root, 0, sum);
        }

Log in to reply
 

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