题目描述:
题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。
代码:
#include <fstream>
#include <stack>
#include <vector>
using namespace std;
struct binaryTreeNode
{
int data;
binaryTreeNode *left;
binaryTreeNode *right;
};
void findPathForInner(int sum,binaryTreeNode *root,vector<int> &path)
{
if(root==NULL)
{
return ;
}
sum-=root->data;
path.push_back(root->data);
if(sum==0 && root->left==NULL && root->right==NULL)
{
vector<int>::iterator iter=path.begin();
while(iter!=path.end())
{
cout<<*iter<<" ";
}
cout<<endl;
return;
}
findPathForInner(sum,root->left,path);
findPathForInner(sum,root->right,path);
sum+=root->data;
path.pop_back();
}
void findPath(int sum,binaryTreeNode *root)
{
if(root==NULL)
{
return ;
}
vector<int> path;
findPathForInner(sum,root,path);
}