版权声明:本文为原创博客,未经允许,请勿转载。 https://blog.csdn.net/u013095333/article/details/88599595
题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的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> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > ans;
vector<int> path;
if(root){
DFS(root, expectNumber, ans, path);
}
return ans;
}
void DFS(TreeNode* root, int expectNumber, vector<vector<int> >& ans, vector<int> path) {
path.push_back(root->val);
if(root->left == NULL && root->right == NULL){
if(expectNumber == root->val){
ans.push_back(path);
}
}
if(root->left){
DFS(root->left, expectNumber-root->val, ans, path);
}
if(root->right){
DFS(root->right, expectNumber-root->val, ans, path);
}
}
};