二叉树求和的所有路径,比如
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10,12和12,5,7
#include<iostream>
#include<string>
#include <stack>
using namespace std;
static int sum(0);
static int count(0);
template<class T>
struct BiNode
{
T data;
struct BiNode<T> *rchild,*lchild;
};
template<class T>
class BiTree
{
public:
BiTree(){
cout<<"int root node"<<endl;
Create(root);
if (NULL != root)
{
cout<<"root="<<root->data<<endl;
}
else
{
cout << "The BinaryTree is empty." << endl;
}
}
~BiTree(){Release(root);}
int Depth(){return Depth(root);}
int FindPath(T i)
{
stack<BiNode<T>*> sta;
return FindPath(i, root, sta);
};
private:
BiNode<T> *root;
void Create(BiNode<T>* &bt);
void Release(BiNode<T> *bt);
int Depth(BiNode<T>* bt);
int FindPath(T i, BiNode<T>* bt, stack<BiNode<T>*> &sta);
};
template <class T>
void BiTree<T>::Release(BiNode<T> *bt)
{
if(bt==NULL)
{
Release(bt->lchild );
Release(bt->rchild );
delete bt;
}
}
//先序遍历构建树
template <class T>
void BiTree<T>::Create(BiNode<T>* &bt)
{
T ch;
cin>>ch;
if(ch== 0)bt=NULL;
else
{
bt=new BiNode<T>;
bt->data =ch;
cout<<"left child"<<endl;
Create(bt->lchild );
cout<<"right child"<<endl;
Create(bt->rchild );
}
}
template <class T>
int BiTree<T>::Depth(BiNode<T>* bt)
{
if (NULL == bt)
{
return 0;
}
int d1 = Depth(bt->lchild);
int d2 = Depth(bt->rchild);
return (d1 > d2 ? d1 : d2)+ 1;
}
//采用回溯法查找路径
template <class T>
int BiTree<T>::FindPath(T i, BiNode<T>* bt, stack<BiNode<T>*> &sta)
{ static int count;
if (NULL != bt)
{
sta.push(bt); //将根节点压栈 ,栈用来保存结果集
}
sum += bt->data;
if (sum == i && bt->lchild == NULL && bt->rchild == NULL)//当求到和且左子树和右子数都为空也就是到了叶节点时,就找到了解
{
//打印结果
stack<BiNode<T>*> sta2(sta);
BiNode<T>* p;
cout << "One of the path is: " ;
while (!sta2.empty())
{
p = sta2.top();
cout << p->data << " ";
sta2.pop();
}
cout << endl;
count ++;
}
//当没有到叶节点时,继续找。
if (NULL != bt->lchild)
{
FindPath(i, bt->lchild, sta);
}
if (NULL != bt->rchild)
{
FindPath(i,bt->rchild, sta);
}
//回溯时,需要回到之前的状态,所以要减去sum,并且弹栈。
sum -= bt->data;
sta.pop();
return count;
}
int main()
{
BiTree<int> a;
cout << "There are " << a.FindPath(22) << " path all." << endl;
system("pause");
return 0;
}