12ms C++ solution


  • 1
    D
    class Solution {
    public:
        void pathSum(TreeNode* root, vector<vector<int>>& result, vector<int>& path, int sum) {
            if(!root) return;
            path.push_back(root -> val);
            if(!root -> left && !root -> right && sum == root -> val) {           //leaf node
                result.push_back(path);
            }
            pathSum(root -> left, result, path, sum - root -> val);
            pathSum(root -> right, result, path, sum - root -> val);
            path.pop_back();
        }
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            vector<vector<int>> result;
            vector<int> path;
            pathSum(root, result, path, sum);
            return result;
        }
    };
    

  • 0
    Z

    it really helps me to solve the problem!!


Log in to reply
 

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