您的位置:首页 > 其它

二叉树(作业)

2009-11-23 14:23 127 查看
1、掌握二叉树的存储方法;

2、掌握二叉树的基本算法。

二:实验内容和要求:

1、编写函数,创建一棵二叉树;

2、编写函数,用递归算法分别求二叉树的各种遍历序列;

三:源代码

]#include <stdio.h>

#include <malloc.h>

typedef struct BiTree

{

char data;

struct BiTree *LChild;

struct BiTree *RChild;

}BiTree;

BiTree * CreateBiTree();    //创建二叉树

void PrintTree(BiTree* bt,int nLayer) ;   //输出二叉树

void   PreOrder(BiTree *root);   //先序遍历

void   InOrder(BiTree *root) ;    //中序遍历

void   PostOrder(BiTree *root); //后序遍历

BiTree * CreateBiTree()   //创建二叉树

{

BiTree *bt;

char ch;

scanf("%c",&ch);

if(ch=='.')

{

bt=NULL;

}

else

{

bt=(BiTree*)malloc(sizeof(BiTree));

bt->data=ch;

bt->LChild=CreateBiTree();

bt->RChild=CreateBiTree();

}

return bt;

}

void PrintTree(BiTree* bt,int nLayer)    //输出二叉树

{

if(bt == NULL) return;

PrintTree(bt->RChild,nLayer+1);

for(int i=0;i<nLayer;i++)

printf("   ");

printf("%c\n",bt->data);

PrintTree(bt->LChild,nLayer+1);

}

void   PreOrder(BiTree *root)    //先序遍历

{

if (root!=NULL)

{

printf("%3c",root ->data);

PreOrder(root ->LChild);

PreOrder(root ->RChild);

}

}

void   InOrder(BiTree *root)   //中序遍历

{

if (root!=NULL)

{

InOrder(root ->LChild);

printf("%3c",root ->data);

InOrder(root ->RChild);

}

}

void   PostOrder(BiTree *root) //后序遍历

{

if(root!=NULL)

{

PostOrder(root ->LChild);

PostOrder(root ->RChild);

printf("%3c",root ->data);

}

}

void main()

{

BiTree *bt;

bt=CreateBiTree();

PrintTree(bt,1);

PreOrder(bt);

printf("\n");

InOrder(bt);

printf("\n");

PostOrder(bt);

printf("\n");

}




一、实验目的:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: