Why trivial case not working?


  • 0
    H

    HI guys

    I am running this code and it is showing error for the trivial case when root = {1} and sum = 0.
    But from my understanding, it should return w/o appending any element , if you see the below code.

      /**
         * Definition for binary tree
         * struct TreeNode {
         *     int val;
         *     TreeNode *left;
         *     TreeNode *right;
         *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
         * };
         */
        class Solution {
        public:
            vector<vector<int> > pathSum(TreeNode *root, int sum) {
             static vector<vector<int> > pathsums;
             
             if(root == NULL)
                return pathsums;
            
            __pathSum(root , sum , pathsums);
            return pathsums;
            }
            
        private:
            void __pathSum(TreeNode *root , int sum , vector<vector<int> > &pathsums){
             static vector<int> sums;
             
             if(root == NULL)
                return ;
            
            if((root->right == NULL) && (root->left == NULL)){
                if((root->val) == (sum)){
                    sums.push_back(root->val);
                    pathsums.push_back(sums);
                    // remove the last element now
                    sums.pop_back();
                }
                return;
            }
            
            sums.push_back(root->val);
            
            __pathSum(root->left , sum-root->val , pathsums);
            __pathSum(root->right , sum-root->val , pathsums);
            
            sums.pop_back();
             
            return;
        }
            
            
        };

Log in to reply
 

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