例子:前序输入 AB##CDF#G#E#### (#表示空,不存在)
#include<iostream>
using namespace std;
typedef struct BiNode
{
char data;
struct BiNode* lchild, * rchild;
}BiNode,*Bitree;
char ch;
int m, n;
typedef struct
{
char data[100];
int front, rear;
}sqqueue;
bool newtree(Bitree& t)//初始化树
{
t = new BiNode;
return 1;
}
void createbitree(Bitree& t)//前序建树
{
t = new BiNode;
cin >> ch;
if (ch == '#') t = NULL;
else
{
t->data = ch;
createbitree(t->lchild);
createbitree(t->rchild);
}
}
int Copy(Bitree t, Bitree &newt)//复制树
{
if (t == NULL)
{
newt = NULL;
return 0;
}
else
{
newt = new BiNode;
newt->data = t->data;
Copy(t->lchild, newt->lchild);
Copy(t->rchild, newt->lchild);
}
return 1;
}
int Depth(Bitree t)//深度
{
if (t == NULL)
return 0;
else
{
m = Depth(t->lchild);
n = Depth(t->rchild);
if (m > n) return(m + 1);
else return (n + 1);
}
}
int Nodecount(Bitree t)//节点数
{
if (t == NULL) return 0;
else return Nodecount(t->lchild) + Nodecount(t->rchild) + 1;
}
int Leadcount(Bitree t)//叶子节点数
{
if (t == NULL) return 0;
if (t->lchild == NULL && t->rchild == NULL)
return 1;
else
return Leadcount(t->lchild) + Leadcount(t->rchild);
}
bool pretree(Bitree t)//前序遍历
{
if (t == NULL) return true;
else
{
cout << t->data;
pretree(t->lchild);
pretree(t->rchild);
}
return 1;
}
bool intree(Bitree t)//中序遍历
{
if (t == NULL) return true;
else
{
intree(t->lchild);
cout << t->data;
intree(t->rchild);
}
return true;
}
bool posttree(Bitree t)//后序遍历
{
if (t == NULL) return true;
else
{
posttree(t->lchild);
posttree(t->rchild);
cout << t->data;
}
return 1;
}
int main()
{
int n;
cin >> n;
Bitree t;
newtree(t);
while (n)
{
if (n == 1)//前序建立二叉树 #表示空
{
cout << "前序建立二叉树 #表示空" << endl;
createbitree(t);
}
if (n == 2)//复制树
{
cout << "复制树" << endl;
Bitree newt;
Copy(t, newt);
}
if (n == 3)//二叉树深度
{
cout << "二叉树深度" << endl;
int a = Depth(t);
cout << a<<endl;
}
if (n == 4)//节点数
{
cout << "节点数" << endl;
int a = Nodecount(t);
cout << a<<endl;
}
if (n == 5)//叶子节点数
{
cout << "叶子节点数"<<endl;
int a = Leadcount(t);
cout << a<<endl;
}
if (n == 6)//前序遍历
{
cout << "前序遍历" << endl;
pretree(t);
cout << endl;
}
if (n == 7)//中序遍历
{
cout << "中序遍历" << endl;
intree(t);
cout << endl;
}
if (n == 8)//后序遍历
{
cout << "后序遍历" << endl;
posttree(t);
cout << endl;
}
cout << "输入n" << endl;;
cin >> n;
}
}