题意
打印二叉树中和为某值的所有路径
分析
dfs 回溯即可。
/**
* 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>> res;
vector<int> tmp;
bool isleaf(TreeNode* node){
return node->left == NULL && node->right == NULL;
}
void dfs(TreeNode* root, int sum, int target){
if(isleaf(root)){
sum += root->val;
if(sum == target){
tmp.push_back(root->val);
res.push_back(tmp);
tmp.pop_back();
return;
}
return;
}
tmp.push_back(root->val);
if(root->left != NULL)dfs(root->left, sum + root->val, target);
if(root->right != NULL)dfs(root->right, sum + root->val, target);
tmp.pop_back();
}
vector<vector<int>> findPath(TreeNode* root, int sum) {
if(root == NULL)return res;
dfs(root, 0, sum);
return res;
}
};