12ms c++ solution


  • 0
    A
    class Solution {
    public:
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            vector<vector<int>> result;
            vector<int> path;
            
            CreatpathSum(root,sum,result,path);
            
            return result;
        }
        
        void CreatpathSum(TreeNode* root, int sum, vector<vector<int>>&result, vector<int> &path) 
        {
            if(root == NULL) return;
            
            if (isLeaf(root) && sum == root->val)
            {
                path.push_back(root->val);
                result.push_back(path);
                path.pop_back();
            }
            
            else
            {
                path.push_back(root->val);
                sum -= root->val;
                
                CreatpathSum(root->left, sum, result,path);
                CreatpathSum(root->right, sum, result,path);
                
                path.pop_back();
            }
        }
        
        inline bool isLeaf(TreeNode* root) {return (!(root->left || root->right));}
    };

Log in to reply
 

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