NewCodeTemplate
This commit is contained in:
35
模板/树/前序遍历路径.cpp
Normal file
35
模板/树/前序遍历路径.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* struct TreeNode {
|
||||
* int val;
|
||||
* TreeNode *left;
|
||||
* TreeNode *right;
|
||||
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
|
||||
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
|
||||
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
|
||||
* };
|
||||
*/
|
||||
class Solution {
|
||||
public:
|
||||
vector<vector<int>> result;
|
||||
vector<int> path;
|
||||
void dfs(TreeNode* root, vector<int>& path, int sum, int target){
|
||||
if(root == nullptr) return;
|
||||
|
||||
path.push_back(root->val);
|
||||
sum += root->val;
|
||||
|
||||
if(sum == target && root->left == nullptr && root->right == nullptr){
|
||||
result.push_back(path);
|
||||
}
|
||||
|
||||
dfs(root->left, path, sum, target);
|
||||
dfs(root->right, path, sum, target);
|
||||
|
||||
path.pop_back();
|
||||
}
|
||||
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
|
||||
dfs(root, path, 0, targetSum);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user