Simple recursive yet efficient enough in cpp

  • 0
    class Solution {
        void traverse(const TreeNode* root, vector<vector<int>>& paths, vector<int> path, int sum)
            int val = root->val;
            sum -= val;
            if(!root->left && !root->right && sum==0) paths.push_back(path);
            if(root->left) traverse(root->left, paths, path, sum);
            if(root->right) traverse(root->right, paths, path, sum);
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            vector<vector<int>> paths;
            if(!root) return paths;
            vector<int> path;
            traverse(root, paths, path, sum);
            return paths;

Log in to reply

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