|
| 1 | +#include <vector> |
| 2 | +#include <iostream> |
| 3 | +#include <algorithm> |
| 4 | +using namespace std; |
| 5 | +struct TreeNode { |
| 6 | + int val; |
| 7 | + TreeNode *left; |
| 8 | + TreeNode *right; |
| 9 | + TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 10 | +}; |
| 11 | +class Solution { |
| 12 | +public: |
| 13 | + vector<vector<int> > pathSum(TreeNode *root, int sum) { |
| 14 | + vector<vector<int>> result; |
| 15 | + vector<int> t; |
| 16 | + pathSum(result, t, root, sum); |
| 17 | + return result; |
| 18 | + } |
| 19 | +private: |
| 20 | + void pathSum(vector<vector<int>> &result, vector<int> cur, TreeNode *root, int sum) { |
| 21 | + if (root == NULL) |
| 22 | + return; |
| 23 | + cur.push_back(root->val); |
| 24 | + sum -= root->val; |
| 25 | + if (isLeft(root) && sum == 0) { |
| 26 | + result.push_back(cur); |
| 27 | + return; |
| 28 | + } |
| 29 | + pathSum(result, cur, root->left, sum); |
| 30 | + pathSum(result, cur, root->right, sum); |
| 31 | + } |
| 32 | + bool isLeft(TreeNode *p) { |
| 33 | + if (p == nullptr) |
| 34 | + return false; |
| 35 | + return p->left == nullptr && p->right == nullptr; |
| 36 | + } |
| 37 | +}; |
| 38 | +TreeNode *mk_node(int val) |
| 39 | +{ |
| 40 | + TreeNode *p = new TreeNode(val); |
| 41 | + return p; |
| 42 | +} |
| 43 | +void mk_child(TreeNode *root, TreeNode *left, TreeNode *right) |
| 44 | +{ |
| 45 | + root->left = left; |
| 46 | + root->right = right; |
| 47 | +} |
| 48 | +void mk_child(TreeNode *root, int left, int right) |
| 49 | +{ |
| 50 | + mk_child(root, mk_node(left), mk_node(right)); |
| 51 | +} |
| 52 | +int main(int argc, char **argv) |
| 53 | +{ |
| 54 | + Solution solution; |
| 55 | + TreeNode *root = mk_node(5); |
| 56 | + mk_child(root, 4, 8); |
| 57 | + TreeNode *left = root->left; |
| 58 | + TreeNode *right = root->right; |
| 59 | + mk_child(left, mk_node(11), nullptr); |
| 60 | + mk_child(left->left, 7, 2); |
| 61 | + mk_child(right, 13, 4); |
| 62 | + mk_child(right->right, 5, 1); |
| 63 | + auto result = solution.pathSum(root, 22); |
| 64 | + cout << "size: " << result.size() << endl; |
| 65 | + for (auto v : result) { |
| 66 | + for_each(v.begin(), v.end(), [](int i){cout << i << " ";}); |
| 67 | + cout << endl; |
| 68 | + } |
| 69 | +} |
0 commit comments