O(n) time 16ms C++ Solution


  • 1
    X
    class Solution {
    private:
        bool hasPathInner(TreeNode *root, int sum){
            int currentVal = sum - root->val;
            if(!root->left && !root->right) {
                if( currentVal == 0) return true;
                return false;
            }
            bool flag = false;
            if(root->left) flag = flag | hasPathInner(root->left, currentVal);
            if(root->right) flag = flag | hasPathInner(root->right, currentVal);
            return flag;
        }
    public:
        bool hasPathSum(TreeNode *root, int sum) {
            if(!root) return false;
            return hasPathInner(root, sum);
        }
    };

Log in to reply
 

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