33,321
社区成员




#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef char ElemType;
const int MaxLength = 30;
typedef struct BiTreeNode
{
ElemType data;
struct BiTreeNode *lchild,*rchild;
}BiTreeNode, *BiTree;
void CreateBiTree(BiTree &T)
{
ElemType ch;
cin >> ch;
if (ch == '#')
T = NULL;
else
{
if (!(T = new BiTreeNode))
exit(OVERFLOW);
T->data = ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
void PreOrder(BiTree &T)
{
if (T != NULL)
{
cout << T->data << ' ';
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void InOrder(BiTree &T)
{
if (T != NULL)
{
InOrder(T->lchild);
cout << T->data << ' ';
InOrder(T->rchild);
}
}
void PostOrder(BiTree &T)
{
if (T != NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout << T->data << ' ';
}
}
void LevelOrder(BiTree T)
{
BiTree Q[MaxLength];
int front = 0, rear = 0;
BiTree p;
if (T)
{
Q[rear] = T;
rear = (rear + 1)%MaxLength;
}
while (front != rear)
{
p = Q[front];
front = (front + 1)%MaxLength;
cout << p->data << ' ';
if (p->lchild)
{
Q[rear] = p->lchild;
rear = (rear + 1)%MaxLength;
}
if (p->rchild)
{
Q[rear] = p->rchild;
rear = (rear + 1)%MaxLength;
}
}
}
bool Complete(BiTree T)
{
BiTree Q[MaxLength];
int front = 0, rear = 0;
BiTree p;
if (T == NULL)
return true;
else
{
Q[rear] = T;
rear = (rear + 1)%MaxLength;
while (front != rear)
{
p = Q[front];
front = (front + 1)%MaxLength;
if (p)
{
Q[rear] = p->lchild;
rear = (rear + 1)%MaxLength;
Q[rear] = p->rchild;
rear = (rear + 1)%MaxLength;
}
else
{
while(front != rear)
{
p = Q[front];
if (p)
return false;
else
return true;
}
}
}
return true;
}
}
int Depth(BiTree T)
{
int depthval, depthleft, depthright;
if (!T)
depthval = 0;
else
{
depthleft = Depth(T->lchild);
depthright = Depth(T->rchild);
depthval = 1 + (depthleft > depthright ? depthleft : depthright);
}
return depthval;
}
int Countleaf(BiTree T)
{
int m,n;
if (!T)
return 0;
if (!T->lchild && !T->rchild)
return 1;
else
{
m = Countleaf(T->lchild);
n = Countleaf(T->rchild);
return (m+n);
}
}
int Countleafs(BiTree T)
{
int m,n;
if (!T)
return 0;
if (!T->lchild && !T->rchild)
return 1;
else
{
m = Countleafs(T->lchild);
n = Countleafs(T->rchild);
return (m + n + 1);
}
}
void main()
{
cout << "Made by Fly!!" << endl;
cout << "请输入二叉树序列,如:AB#C#D##" << endl;
BiTree tree;
CreateBiTree (tree);
cout << "二叉树创建完成!" << endl;
cout << "先序遍历二叉树输出结果:";
PreOrder (tree);
cout << endl;
cout << "中序遍历二叉树输出结果:";
InOrder (tree);
cout << endl;
cout<<"后序遍历二叉树输出结果:";
PostOrder (tree);
cout << endl;
cout << "层次遍历二叉树输出结果:";
LevelOrder (tree);
cout << endl;
cout << "层次遍历二叉树判定是否为完全二叉树:"<<endl;
bool t = Complete(tree);
if(t)
{
cout << "此二叉树是完全二叉树。" << endl;
}
else
{
cout << "此二叉树不是完全二叉树。" << endl;
}
cout << "此二叉树的深度为:";
int m = Depth(tree);
cout << m << endl;
cout << "此二叉树的总结点个数为:";
int n=Countleafs(tree);
cout << n << endl;
cout << "此二叉树的叶子结点个数为:";
int a = Countleaf(tree);
cout << a << endl;
}