题目:
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:
先序遍历二叉树的结点,当访问某一结点时,把该结点添加到路径中,并且累加该路径的值。
1、当该结点是叶子结点,并且路径值等于输入的整数,把路径打印出来。
2、当前结点不是叶子结点时,左右子结点不为空时继续访问它们。
3、当前结点访问完后,要在路径上退出该节点。
/*
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>> PathAll;
vector<int> path;
int pathsum=0;
if(root!=nullptr)
find(root,expectNumber,PathAll,path,pathsum);
return PathAll;
}
void find(TreeNode *root,int expectNumber,
vector<vector<int >>&PathAll,vector<int> &path,int pathsum)
{
pathsum+=root->val;
path.push_back(root->val);
if(pathsum==expectNumber&&root->left==nullptr&&root->right==nullptr)
//叶子结点且路径值满足条件
PathAll.push_back(path);//把路径存入二维数组中
//不是叶子结点,遍历它的子结点
if(root->left!=nullptr)
find(root->left,expectNumber,PathAll,path,pathsum);
if(root->right!=nullptr)
find(root->right,expectNumber,PathAll,path,pathsum);
path.pop_back();//递归结束时要在路径中删除当前结点,回到它的父结点
}
};