JZ24 二叉树中和为某一值的路径

本文最后更新于:2022年4月9日 中午

image-20211008102237901

Solution

  • 回溯法
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
31
32
33
34
35
36
37
38
39
40
41
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
res.clear();
vector<int> path;
if (root == nullptr) return res;

backtrack(root, expectNumber, path);
return res;
}
private:
vector<vector<int>> res;

void backtrack(TreeNode* root, int target, vector<int> path) {
path.push_back(root->val);
target -= root->val;
if (target == 0 && root->left == nullptr && root->right == nullptr) {
res.push_back(path);
return;
}
if (root == nullptr || target < 0) return;

if (root->left) {
backtrack(root->left, target, path);
}
if (root->right) {
backtrack(root->right, target, path);
}
path.pop_back();
return;
}
};