开门见码
代码中包含了二叉树的一些基本操作,reverse函数为求逆路径的函数
#include <bits/stdc++.h>
using namespace std;
const int MaxSize = 55;
typedef char ElemType;
struct Node {
ElemType data; //值
Node *l,*r;
Node *f;
};
void CreateTree(Node *&t,ElemType s[],Node *f) //建树
{
ElemType temp;
static int i = 0;
temp = s[i++];
if(temp == '*')
t = NULL;
else {
t = new Node;
if(!t)
exit(-1);
t->data = temp;
t->f = f;
CreateTree(t->l,s,t);
CreateTree(t->r,s,t);
}
}
void PreOrderTree(Node *t) // 先序递归遍历
{
if( t) {
cout << t->data;
PreOrderTree(t->l);
PreOrderTree(t->r);
}
}
void InOrderTree(Node *t) //中序递归遍历
{
if( t){
InOrderTree(t->l);
cout << t->data;
InOrderTree(t->r);
}
}
void LastOrderTree(Node *t) //后续递归遍历
{
if( t){
LastOrderTree(t->l);
LastOrderTree(t->r);
cout << t->data;
}
}
void InOrderTree_NotRecur(Node *t) //中序非递归遍历
{
stack< Node *> s;
s.push(t);
while(!s.empty()) {
while(s.top())
s.push(s.top()->l);
s.pop(); //空指针退栈
if(!s.empty()) {
printf("%c",s.top()->data);
Node *Top = s.top();
s.pop();
s.push(Top->r);
}
}
}
void Show_path(Node *t)
{
if(t->f)
Show_path(t->f);
printf("->%c",t->data);
}
void Find_Node(Node *t,ElemType a) // 求指定节点的路径
{
if(t == NULL)
return;
if(t->data == a) {
Show_path(t);
return ;
}
Find_Node(t->l,a);
Find_Node(t->r,a);
}
int HeightTree(Node *t)
{
if(t == NULL)
return 0;
else {
if(t->l == NULL && t->r == NULL)
return 1;
else
return 1+max(HeightTree(t->l),HeightTree(t->r));
}
}
void FreeTree(Node *t)
{
if(t == NULL)
return;
FreeTree(t->l);
FreeTree(t->r);
delete t;
}
ElemType ans[MaxSize]; // 存储最长的逆序序列
int maxn = 0;
void Reverse(Node *t,ElemType b[],int k) // k用做数组下标
{
if( t){
b[k++] = t->data;
if(t->l == NULL && t->r == NULL) {
if(k > maxn) {
maxn = k;
strcpy(ans,b);
}
for(int i=k-1; i>=0; i--)
cout << b[i] << " ";
cout << endl;
}
else {
Reverse(t->l,b,k);
Reverse(t->r,b,k);
}
}
}
int main()
{
ElemType a[]="ABD**EHJ**KL**M*N***CF**G*I**";
Node *rt;
CreateTree(rt,a,NULL); // 建立二叉树:A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))
cout << "先序递归遍历二叉树\n";
PreOrderTree(rt); //先序递归遍历二叉树
cout << endl;
cout << "中序递归遍历二叉树\n";
InOrderTree(rt); //中序递归遍历二叉树
cout << endl;
cout << "中序非递归遍历二叉树\n";
InOrderTree_NotRecur(rt); //中序非递归遍历二叉树
cout << endl;
cout << "后序递归遍历二叉树\n";
LastOrderTree(rt); //后序递归遍历二叉树
cout << endl;
cout << "求从根节点到节点L的路径\n";
Find_Node(rt,'L'); //求指定节点的路径
cout << endl;
// 二叉树先序遍历输出逆路径
cout << "先序遍历逆路径\n";
ElemType b[MaxSize];
maxn = 0;
Reverse(rt,b,0);
cout << "最大深度 : (最长逆路径) " << maxn << endl;
for(int i=maxn-1; i>=0; i--)
cout << ans[i] << " ";
cout << endl;
}