数据结构创建一棵树的c语言代码怎么写?

如题所述

刚刚回答了一个类似的问题,以下代码供参考:
#include "stdio.h"
#include "stdlib.h"
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef char TElemType;
typedef int Status;
typedef struct BiTNode { // 结点结构
TElemType data;
struct BiTNode *lchild, *rchild;
// 左右孩子指针
} BiTNode, *BiTree;

//以下是建立二叉树存储结构,空节点输入作为#结束标识
Status CreateBiTree(BiTree &T) {
//请将该算法补充完整,参见第6章课件算法或课本
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 OK;

} // CreateBiTree
void Preorder(BiTree T)
{
if(T)
{
printf("%c",T->data);
Preorder(T->lchild);
Preorder(T->rchild);
}
}

void Inorder(BiTree T)
{ // 中序遍历二叉树
//请将该算法补充完整,参见第6章课件算法
if(T)
{
Inorder(T->lchild);
printf("%c",T->data);
Inorder(T->rchild);
}
}
void Postorder(BiTree T)
{ // 后序遍历二叉树
//请将该算法补充完整,参见第6章课件算法
if(T)
{
Postorder(T->lchild);
Postorder(T->rchild);
printf("%c",T->data);
}
}

//以下是求叶子结点数
void CountLeaf(BiTree T,int& count){
//请将该算法补充完整,参见第6章课件算法
if(T){
if((!T->lchild)&&(!T->rchild))
count++;
CountLeaf(T->lchild,count);
CountLeaf(T->rchild,count);
}
}

//以下是求二叉树的深度
int Depth(BiTree T ){
//请将该算法补充完整,参见第6章课件算法
int depthval,depthLeft,depthRight;
if(!T) depthval=0;
else{
depthLeft = Depth(T->lchild);
depthRight = Depth(T->rchild);
if(depthLeft>depthRight)depthval = 1+depthLeft;
else depthval = 1+depthRight;
}
return depthval;
}

void main(){
BiTree T;
int s=0,d;
printf("\n creat of the bitree:\n");
CreateBiTree(T);
printf("\n output result of Preorder:\n");
Preorder(T);
CountLeaf(T,s);
d=Depth(T);
printf("\n leaves=%d\n",s);
printf("\n depth=%d\n",d);
}
温馨提示:答案为网友推荐,仅供参考