//二叉树的创建和基本操作
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1
typedef int Status;
typedef char TElemType;
typedef struct BitNode{
TElemType data;
struct BitNode *lchild,*rchild;
}BitNode,*BitTree;
Status CreateBitTree(BitTree &T){
//创建一颗二叉树T,按先序遍历的方式创建
char ch;
scanf("%c",&ch);
if(ch=='#') T=NULL;
else{
if(!(T=(BitNode *)malloc(sizeof(BitNode)))) return OVERFLOW;
T->data=ch;
CreateBitTree(T->lchild);
CreateBitTree(T->rchild);
}//if
return OK;
}//CreateBitTree
void PreOrderTraverse(BitTree T){
//先序遍历二叉树T
if(!T) return;
printf("%c ",T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}//PreOrderTraverse
void InOrderTraverse(BitTree T){
//中序遍历二叉树T
if(!T) return;
InOrderTraverse(T->lchild);
printf("%c ",T->data);
InOrderTraverse(T->rchild);
}//InOrderTraverse
void PostOrderTraverse(BitTree T){
//后序遍历二叉树T
if(!T) return;
PostOrderTraverse(T->lchild);
PostOrderTraverse(T->rchild);
printf("%c ",T->data);
}//InOrderTraverse
int CountNode(BitTree T){
//求二叉树T的结点总数
if(!T) return 0;
return CountNode(T->lchild)+CountNode(T->rchild)+1;
}//CountNode
int MyMax(int a,int b){
if(a>=b) return a;
return b;
}//MyMax
int GetHigh(BitTree T){
//求二叉树T的高度
if(!T) return 0;
return MyMax(GetHigh(T->lchild),GetHigh(T->rchild))+1;
}//GetHigh
int CountLeafNode(BitTree T){
//求二叉树T的叶子结点总数
if(!T) return 0;
if(!T->lchild&&!T->rchild) return 1;
return CountLeafNode(T->lchild)+CountLeafNode(T->rchild);
}//CountNode
main()
{
BitTree T;
CreateBitTree(T);
printf("\n先序遍历:");
PreOrderTraverse(T);
printf("\n中序遍历:");
InOrderTraverse(T);
printf("\n后序遍历:");
PostOrderTraverse(T);
printf("\n二叉树的结点数为:%d",CountNode(T));
printf("\n二叉树的高度为:%d",GetHigh(T));
printf("\n二叉树的叶子结点数为:%d",CountLeafNode(T));
printf("\n");
}
二叉树的基本操作
最新推荐文章于 2023-02-17 15:20:57 发布