题目描述
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
带记忆的DFS
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
vector<vector<int>> res;
vector<int> path;
void find(TreeNode* root,int sum){
//这两句可加可不加
if(sum < root->val)// 当前值不适合
return;
//路径输入
path.push_back(root->val);
//判断是否符合条件
if(!root->left && !root->right && sum == root->val)//到达叶子节点
res.push_back(path);
else{
if(root->left)//查找左子树
find(root->left,sum-root->val);
if(root->right)//查找右子树
find(root->right,sum-root->val);
}
//删除path的最后一个元素,它表示当前叶节点和根节点形成的路径不满足条件,
//删除叶节点,返回它的父节点
path.pop_back();
}
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root==NULL)
return res;
find(root,expectNumber);//查找符合的路径
sort(res.begin(),res.end(),[](const vector<int> &a,const vector<int> &b) {return a.size()>b.size();});//降序排序
return res;
}
};
参考链接: