#include <iostream>
using namespace std;
#include <malloc.h>
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAX_TREE_SIZE 100//二叉树的最大结点数
typedef char ElemType;
typedef int Status;
typedef struct BiTNode{
ElemType data;
struct BiTNode *lchild,*rchild;//左右孩子指针
}BiTNode,*BiTree;//结点类型,指针类型
int count=0;//CountLeaf函数用到的全局变量
BiTree CreateBiTree(BiTree &T)//按照先序序列建立二叉树的二叉链表
{//按先序次序输入二叉树中结点的值(一个字符),#表示空树
//构造二叉链表表示的二叉树T
char ch;
scanf("%c",&ch);
if(ch=='#')
T = NULL;//(出口)
else
{
if(!(T = (BiTNode *)malloc(sizeof(BiTNode))))//要一个二叉树结点
exit(OVERFLOW);
T -> data = ch;//生成根结点
CreateBiTree(T->lchild);//构造左子树
CreateBiTree(T->rchild);//构造右子树
}
return T;
}
Status InorderTraverse(BiTree T)//采用二叉链表存储结构,中序遍历二叉树
{
if(T==NULL)
{
return ERROR;
}
else
{
InorderTraverse(T->lchild);//遍历左子树
printf("%c",T->data);
InorderTraverse(T->rchild);//遍历右子树
}
return OK;
}
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)//需要在函数之前定义全局变量count
{
if(T)
{
if((!T->lchild)&&(!T->rchild))
{
count++;
}
else
{
CountLeaf(T->lchild);
CountLeaf(T->rchild);
}
}
return count;
}
void Exchange(BiTree T)
{
BiTree p;
if(T)
{
p=T->lchild;
T->lchild=T->rchild;
T->rchild=p;
Exchange(T->lchild);
Exchange(T->rchild);
}
}
Status Like(BiTree T1,BiTree T2)
{
if((T1==NULL)&&(T2==NULL))
return TRUE;
else if((T1==NULL)||(T2==NULL))
return FALSE;
else
return (Like(T1->lchild,T2->lchild)) && (Like(T1->rchild,T2->rchild));
}
PreOrder(BiTree T,int i)
{
if(T)
{
T->data = 1;
PreOrder(T->lchild,i+1);
PreOrder(T->rchild,i+1);
cout<<i;
}
}
/*void CountLeaf(BiTree T,int &count)
{
if(T)
{
if((!T->lchild)&&(!T->rchild))
count++;
CountLeaf(T->lchild,count);
CountLeaf(T->rchild,count);
}
}*/
int main()
{
BiTree T,T1,T2;
int t,i;
cout << "请按照先序方式输入二叉树T的结点元素;" << endl;
CreateBiTree(T);
getchar();
cout << "创建成功的二叉树T中序序列为;" <<endl;
InorderTraverse(T);
cout << endl<<"此二叉树T的深度为:" <<Depth(T)<<endl;
cout << "此二叉树T的叶子结点个数为:" <<CountLeaf(T)<<endl;
/*cout<<count<<endl;*/
Exchange(T);
cout << "二叉树T所有结点的左右子树相互交换后的中序遍历为:" <<endl;
InorderTraverse(T);
cout<<"按先序遍历结点,各结点的层次编号为:"<<endl;
PreOrder(T,1);
cout <<endl<< "请输入需要判断是否相似的二叉树T1的结点元素:" <<endl;
T1 = (BiTNode *)malloc(sizeof(BiTNode));
T1=CreateBiTree(T);
getchar();
cout <<endl<< "请输入需要判断是否相似的二叉树T2的结点元素:" <<endl;
T2 = (BiTNode *)malloc(sizeof(BiTNode));
T2=CreateBiTree(T);
t=Like(T1,T2);
if(t==TRUE)
cout<<"T2与T1相似!"<<endl;
else
cout<<"T2与T1不相似!"<<endl;
return 0;
}