c语言二叉树基本操作
编译器为vs2013
#include "stdafx.h"
#include<malloc.h>
#include<stdlib.h>
#define OVERFLOW -1
typedef char BElemType;
typedef int Status;
typedef struct BiTree{
BElemType data;
struct BiTree *lchild,*rchild;
}BitNode,*BinTree;
//函数声明
void CreatTree(BinTree &T); //构建二叉树并赋值
void PreOrderTaverse(BinTree T); //先序遍历二叉树并输出
void InOrderTaverse(BinTree T); //中序遍历二叉树并输出
void PostOrderTaverse(BinTree T); //后序遍历二叉树并输出
Status DepthTree(BinTree T); //返回树的深度
Status LeafNode(BinTree T, int &leaves); //返回叶子结点个数
Status TreeNode(BinTree T, int &node); //返回节点总数
int main()
{
int h, leaves=0, node=0;
BinTree T;
CreatTree(T);
PreOrderTaverse(T);
printf("\n");
InOrderTaverse(T);
printf("\n");
PostOrderTaverse(T);
printf("\n");
h=DepthTree(T);
leaves=LeafNode(T,leaves);
node = TreeNode(T,node);
printf("树的高度为%d\n叶子节点数为%d\n节点总数为%d\n", h, leaves, node);
}
//构建二叉树并赋值
void CreatTree(BinTree &T)
{
BElemType ch;
scanf_s("%c", &ch);
if (ch== ' ')
T = NULL;
else
{
if (!(T = (BinTree)malloc(sizeof(BitNode))))
exit(OVERFLOW);
T->data = ch;
CreatTree(T->lchild);
CreatTree(T->rchild);
}
}
//先序遍历二叉树并输出
void PreOrderTaverse(BinTree T)
{
if (T)
{
printf("%c ", T->data);
PreOrderTaverse(T->lchild);
PreOrderTaverse(T->rchild);
}
}
//中序遍历二叉树并输出
void InOrderTaverse(BinTree T)
{
if (T)
{
InOrderTaverse(T->lchild);
printf("%c ", T->data);
InOrderTaverse(T->rchild);
}
}
//后序遍历二叉树并输出
void PostOrderTaverse(BinTree T)
{
if (T)
{
PostOrderTaverse(T->lchild);
PostOrderTaverse(T->rchild);
printf("%c ", T->data);
}
}
//返回树的深度
Status DepthTree(BinTree T)
{
int dl,dr,deep;
if (!T)
deep = 0;
else if ((T->lchild == NULL)&&(T->rchild == NULL))
deep = 1;
else
{
dl=DepthTree(T->lchild);
dr=DepthTree(T->rchild);
deep = 1 + (dl > dr ? dl : dr);
}
return deep;
}
//返回叶子结点个数
Status LeafNode(BinTree T,int &leaves)
{
if (T)
{
if ((T->lchild == NULL) && (T->rchild == NULL))
leaves++;
LeafNode(T->lchild, leaves);
LeafNode(T->rchild, leaves);
}
return leaves;
}
//返回节点总数
Status TreeNode(BinTree T,int &node)
{
if (T)
{
node++;
TreeNode(T->lchild, node);
TreeNode(T->rchild, node);
}
return node;
}