题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
思路
回溯思想。注意是从根节点到叶结点的序列和。
代码
/*
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>> res;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<int> tmp;
dfs(root, expectNumber, tmp);
return res;
}
void dfs(TreeNode* root,int sum, vector<int> tmp){
if (root == nullptr) return;
tmp.emplace_back(root->val);
sum = sum - root->val;
if (root->left == nullptr && root->right == nullptr && sum == 0){
res.emplace_back(tmp);
}
if (root->left) dfs(root->left, sum, tmp);
if (root->right) dfs(root->right, sum, tmp);
}
};