题目描述:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
实现代码:
/*
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> > AllPath;
vector<int> OnePath;
int currentSum = 0;
if(root == nullptr)
return AllPath;
FindPath1(AllPath,root,expectNumber,OnePath,currentSum);
return AllPath;
}
void FindPath1(vector<vector<int> > &AllPath,TreeNode* root,int expectNumber,vector<int> &OnePath,int currentSum)
{
currentSum+=root->val;
OnePath.push_back(root->val);
if(currentSum==expectNumber && IsLeaf(root))
AllPath.push_back(OnePath);
if(root->left!=nullptr)
FindPath1(AllPath,root->left,expectNumber,OnePath,currentSum);
if(root->right!=nullptr)
FindPath1(AllPath,root->right,expectNumber,OnePath,currentSum);
OnePath.pop_back();
}
bool IsLeaf(TreeNode* root)
{
if(root->left==nullptr&&root->right==nullptr)
return true;
else
return false;
}
};