# 23 二叉树中和为某一值的路径 + 回溯法深入总结

## 题目描述

```/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void helper(vector<vector<int> > &result,vector<int> &tmp,TreeNode* root,int expectNumber){
if(root == nullptr){
return;
}
expectNumber = expectNumber - root->val;
tmp.push_back(root -> val);
if(root -> left == nullptr && root -> right == nullptr){//必须叶子节点才返回
if(expectNumber == 0){
result.push_back(tmp);
tmp.pop_back();
return;
}
else{
tmp.pop_back();
return;
}
}

helper(result,tmp,root -> left,expectNumber);
helper(result,tmp,root -> right,expectNumber);
tmp.pop_back();

}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > result;
vector<int> tmp;
if(root == nullptr){
return result;
}
helper(result,tmp,root,expectNumber);
return result;
}
};```

```/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void helper(vector<vector<int> > &result,vector<int> &tmp,TreeNode* root,int expectNumber){
if(root == nullptr){
return;
}
expectNumber = expectNumber - root->val;
tmp.push_back(root -> val);
if(expectNumber == 0 && root -> left == nullptr && root -> right == nullptr){//必须叶子节点才返回
result.push_back(tmp);
}

helper(result,tmp,root -> left,expectNumber);
helper(result,tmp,root -> right,expectNumber);
tmp.pop_back();

}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > result;
vector<int> tmp;
if(root == nullptr){
return result;
}
helper(result,tmp,root,expectNumber);
return result;
}
};```

```class Solution {
vector<vector<int> >allRes;
vector<int> tmp;
void dfsFind(TreeNode * node , int left){
tmp.push_back(node->val);
if(left-node->val == 0 && !node->left && !node->right)
allRes.push_back(tmp);
else {
if(node->left) dfsFind(node->left, left-node->val);
if(node->right) dfsFind(node->right, left-node->val);
}
tmp.pop_back();
}
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root) dfsFind(root, expectNumber);
return allRes;
}
};```

23 二叉树中和为某一值的路径 + 回溯法深入总结

(0)
(0)

0条