Recursion code not working C++


  • 0
    N
    class Solution {
    public:
        bool hasPathSum(TreeNode* root, int sum) {
            if(!root) return false;
            vector<int> result;
            sumRec(root, result, 0);
            for(int i = 0; i<result.size(); i++){
                if(result[i] == sum) return true;
                return false;
            }
            return false;
        }
        void sumRec(TreeNode* root, vector<int> & res, int n){
        
            if(!root->left && !root->right){
                res.push_back(n+root->val);
                return;
            }
            if(root->left){
                sumRec(root->left, res, n+root->val);
            }
            if(root->right){
                sumRec(root->right, res, n+root->val);
            }
            return;
        }
    };
    

    Seems like my code only travese the left most branch of the tree, I can't figure out why.


Log in to reply
 

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