LeetCode-Path Sum II

思路比较简单,在遍历的基础上加入一个变量来跟踪路径即可(记得及时加入和弹出路径)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> paths;
if(root==nullptr) return paths;
vector<int> path;
helper(root,sum,path,paths);
return paths;
}
void helper(TreeNode* root,int sum,vector<int> &path,vector<vector<int>> &paths){
if(root==nullptr) return;
path.push_back(root->val);
if(root->left==nullptr && root->right==nullptr && sum==root->val){
vector<int> *tPath=new vector<int>(path);
paths.push_back(*tPath);
}
helper(root->left,sum-root->val,path,paths);
helper(root->right,sum-root->val,path,paths);
path.pop_back();
}
};