4.29 数据结构 二叉树
手动输入节点值,二叉树的前序、中序、后序遍历及销毁 并计算二叉树的节点数
运行结果截图:
代码:
/*许沐 20760204
4.28 二叉树 */
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
#define MAXSIZE 100
typedef int SqBiTree[MAXSIZE];
SqBiTree bt;
typedef struct BTNode
{
int data;
struct BTNode* lChild;
struct BTNode* rChild;
}BiTNode;
void CreateBiTree(BiTNode** T)
{
int ch;
scanf_s("%d", &ch);
if (ch < 0)
{
*T = NULL;
return;
}
else
{
*T = (BiTNode*)malloc(sizeof(BiTNode));
(*T)->data = ch;
printf("请输入%d的左子节点:", ch);
CreateBiTree(&((*T)->lChild));
printf("请输入%d的右子节点:", ch);
CreateBiTree(&((*T)->rChild));
}
return;
}
void PreOrderBiTree(BiTNode* T) //先序遍历二叉树
{
if (T == NULL)
return;
else
{
printf("%2d", T->data);
PreOrderBiTree(T->lChild);
PreOrderBiTree(T->lChild);
}
}
void MiddleOrderBiTree(BiTNode* T) //中序遍历二叉树
{
if (T == NULL)
return;
else
{
MiddleOrderBiTree(T->lChild);
printf("%2d", T->data);
MiddleOrderBiTree(T->rChild);
}
}
void PostOrderBiTree(BiTNode* T) //后序遍历二叉树
{
if (T == NULL)
return;
else
{
PostOrderBiTree(T->lChild);
PostOrderBiTree(T->rChild);
printf("%2d", T->data);
}
}
int LeafCount(BiTNode* T) //计算叶子节点个数
{
static int l = 0;
if (T != NULL)
{
if (T->lChild == NULL && T->rChild == NULL)
l++;
LeafCount(T->lChild);
LeafCount(T->rChild);
}
return l;
}
void FreeTree(BiTNode* T) //二叉树的销毁
{
if (T!=NULL)
{
if (T->lChild)
{
FreeTree(T->lChild);
T->lChild = NULL;
}
if (T->rChild)
{
FreeTree(T->rChild);
T->rChild = NULL;
}
if (T != NULL)
{
free(T);
T = NULL;
}
}
}
int main()
{
BiTNode* T;
T = NULL;
int nLeafCount = 0;
printf("请输入第一个节点的值,(-1表示没有叶节点):\n");
CreateBiTree(&T);
printf("先序遍历二叉树:");
PreOrderBiTree(T);
printf("\n");
printf("中序遍历二叉树:");
MiddleOrderBiTree(T);
printf("\n");
printf("后序遍历二叉树:");
PostOrderBiTree(T);
printf("\n");
nLeafCount = LeafCount(T);;
printf("叶子节点的个数为%d", nLeafCount);
FreeTree(T);
return 0;
}