[LeetCode] 113. Path Sum II

来源:互联网 发布:天津seo平台 编辑:程序博客网 时间:2024/06/05 00:39
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.For example:Given the below binary tree and `sum = 22`,
              5             / \            4   8           /   / \          11  13  4         /  \    / \        7    2  5   1
return
[   [5,4,11,2],   [5,8,4,5]]
class Solution {public:   vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int>> paths;        if (root == nullptr) return paths;        if (root->left == nullptr && root->right == nullptr) {            if (sum == root->val)                return {{root->val}};        }        auto lpath = pathSum(root->left, sum - root->val);        for (auto path : lpath) {            vector<int> comb;            comb.push_back(root->val);            comb.insert(comb.end(), path.begin(), path.end());            paths.push_back(move(comb));        }        auto rpath = pathSum(root->right, sum - root->val);        for (auto path : rpath) {            vector<int> comb;            comb.push_back(root->val);            comb.insert(comb.end(), path.begin(), path.end());            paths.push_back(move(comb));        }        return paths;    }};
class Solution {public:    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int>> paths;        vector<int> path;        __pathSum(root, sum, paths, path);        return paths;    }private:    void __pathSum(TreeNode *root, int sum, vector<vector<int>> &paths, vector<int> &path) {        if (root == nullptr) return;        path.push_back(root->val);        if (root->left == nullptr && root->right == nullptr) {            if (sum == root->val) {                paths.push_back(path);                path.pop_back();                return;            }        }        __pathSum(root->left, sum - root->val, paths, path);        __pathSum(root->right, sum - root->val, paths, path);        path.pop_back();    }};
原创粉丝点击