声明:
这是转载的,别人写的很不错的二叉树
链接:https://www.cnblogs.com/liuamin/p/6269950.html
上代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "BTree.h"
#include "Queue.h"
/**
* Created by on 2019/9/24.
*/
/**
*
* @param *T 指针的指针,树初始化完成后还要给别的函数用
* @return
*/
bool createBiTree(BTree *T)
{
ElementType ch;
ch = getchar();
if(ch == '#')
{
*T = NULL;
}
else
{
*T = (BTree)malloc(sizeof(BTreeNode));
if(!*T)
{
printf("Memory allocated Failure!\n");
exit(-1);
}
(*T)->data = ch;
createBiTree(&(*T)->leftChild);
createBiTree(&(*T)->rightChild);
}
}
void preOrderTree(BTree T)
{
if(NULL == T)
{
return;
}
else
{
putchar(T->data);
preOrderTree(T->leftChild);
preOrderTree(T->rightChild);
}
}
void inOrderTree(BTree T)
{
if(NULL == T)
{
return;
}
else
{
inOrderTree(T->leftChild);
putchar(T->data);
inOrderTree(T->rightChild);
}
}
void postOrderTree(BTree T)
{
if(NULL == T)
{
return;
}
else
{
postOrderTree(T->leftChild);
postOrderTree(T->rightChild);
putchar(T->data);
}
}
int getLeafCnt(BTree T)
{
if(NULL == T)
return 0;
if(T->leftChild == NULL && T->rightChild == NULL)
return 1;
//递归整个树的叶子节点个数 = 左子树叶子节点的个数 + 右子树叶子节点的个数
return getLeafCnt(T->leftChild) + getLeafCnt(T->rightChild);
}
int getTreeHeight(BTree T)
{
int height = 0;
if(T)
{
int lh = getTreeHeight(T->leftChild);
int rh = getTreeHeight(T->rightChild);
height = (lh >= rh) ? lh+1 : rh+1;
}
return height;
}
void levelOrderTraverse(BTree T)
{
if(NULL == T)
{
printf("Tree is Empty!\n");
return;
}
QueuePtr Q = (QueuePtr)malloc(sizeof(Queue));
if(!Q)
{
printf("Memory allocate to queue failed!\n");
exit(-1);
}
BTree temp;
//1.初始化,树根节点入队
Q->front =0;
Q->rear =0;
Q->queue[Q->rear++] = T;
//2.队列不为空
while(Q->front != Q->rear)
{
temp = Q->queue[(Q->front++)%MAXSIZE];
printf("%c ", temp->data);
if(temp->leftChild)
{
if((Q->rear+1)%MAXSIZE == Q->rear)
{
printf("队列满!\n");
exit(-1);
}
Q->queue[(Q->rear++)%MAXSIZE] = temp->leftChild;
}
if(temp->rightChild)
{
if((Q->rear+1)%MAXSIZE == Q->rear)
{
printf("队列满!\n");
exit(-1);
}
Q->queue[(Q->rear++)%MAXSIZE] = temp->rightChild;
}
}
}
int main() {
BTree T = NULL;
printf("请按前序遍历输入二叉树的节点数据:\n");
createBiTree(&T);
printf("\n中序遍历结果为: \n");
inOrderTree(T);
int leafNum = getLeafCnt(T);
printf("\n共有叶子结点:%d个\n",leafNum);
int height = getTreeHeight(T);
printf("\n树共有:%d层。\n", height);
printf("按层遍历输出开始:\n");
levelOrderTraverse(T);
printf("\ndone!\n");
return 0;
}