1: /**
2: * Definition for a binary tree node.
3: * struct TreeNode {
4: * int val;
5: * TreeNode *left;
6: * TreeNode *right;
7: * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8: * };
9: */
10: class Solution {
11: public:
12: vector<vector<int>> pathSum(TreeNode* root, int sum) {
13: vector<vector<int>> res;
14: vector<int> sol;
15: helper(root, sum, sol, res);
16: return res;
17: }
18: void helper(TreeNode *root, int sum, vector<int> &sol, vector<vector<int>> &res) {
19: if (root == NULL) return;
20: sol.push_back(root->val);
21: if (!root->left && !root->right && sum == root->val)
22: res.push_back(sol);
23: helper(root->left, sum-root->val, sol, res);
24: helper(root->right, sum-root->val, sol, res);
25: sol.pop_back();
26: return;
27: }
28: };
Sunday, June 26, 2016
113. Path Sum II
Typical DFS problem. I was trying to prune the algorithm but it turns out I don't have to. The code is much concise without pruning and the performance isn't bad (16ms)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment