求一个用C语言写的建立二叉树。并且先序中序后序遍历这个二叉树

论坛 期权论坛 期权     
悲剧故土1   2018-4-26 13:59   1993   3
分享到 :
0 人收藏

3 个回复

倒序浏览
2#
TragedyHome  3级会员 | 2018-4-30 01:55:46 发帖IP地址来自
其实这个程序很简单的。 代码如下:

#include
#include
#define MAX_TREE_SIZE  100
typedef struct {
int i;
}TElemType;
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
int CreateBiTree(BiTree &T)
{
char ch;
scanf("%c",&ch);
getchar();
if(ch==' '||ch=='\n')
{
  T=NULL;
}
else{
  T=(BiTNode *)malloc(sizeof(BiTNode));
  T->data=ch;
  CreateBiTree(T->lchild);
  CreateBiTree(T->rchild);
}
return 1;
}//CreateBiTree()
int Visit(char ch)
{
printf("%c",ch);
return 1;
}
int PreOrderTraverse(BiTree T,int (* Visit)(char ch))
{
if(T)
{
  if(Visit(T->data))
   if(PreOrderTraverse(T->lchild,Visit))
    if(PreOrderTraverse(T->rchild,Visit)) return 1;
}else return 1;
}
int InOrderTraverse(BiTree T,int (* Visit)(char ch))
{
if(T)
{
   if(InOrderTraverse(T->lchild,Visit))
    if(Visit(T->data))
     if(InOrderTraverse(T->rchild,Visit)) return 1;
}else return 1;
}
int PostOrderTraverse(BiTree T,int(* Visit)(char ch))
{
if(T)
{
  if(PostOrderTraverse(T->lchild,Visit))
   if(PostOrderTraverse(T->rchild,Visit))
    if(Visit(T->data))  return 1;
}else return 1;
}
void  main()
{
BiTree  T;
printf("从根节点输入二叉树,存储方式采用中序遍历,无分支请输入空格:\n");
CreateBiTree(T);
printf("先序遍历为:");
PreOrderTraverse(T,Visit);
printf("\n");
printf("中序遍历为:");
InOrderTraverse(T,Visit);
printf("\n");
printf("后序遍历为:");
PostOrderTraverse(T,Visit);
}
3#
幸福着孤单  2级吧友 | 2018-4-30 01:55:47 发帖IP地址来自
#include
#include
#include
//二叉树数据结构定义
typedef struct BiNode
{
char data;
struct BiNode *LChild;
    struct BiNode *RChild;
}BiTNode,*BiTree;
//递归法建立二叉树
void CreateBiTree(BiTree *bt)
{
char ch;
ch = getchar();
if(ch == ' ')
{
  *bt = NULL;
}
else
{
  *bt = (BiTree)malloc(sizeof(BiTNode));
  (*bt)->data = ch;
  CreateBiTree(&((*bt)->LChild));
        CreateBiTree(&((*bt)->RChild));
}
}

//递归法先序遍历二叉树
void PreOrderTree(BiTree root)
{
    if(root != NULL)
{
  printf("%c  ",root->data);
  PreOrderTree(root->LChild);
  PreOrderTree(root->RChild);
}
}
//递归法中序遍历二叉树
void InOrderTree(BiTree root)
{
    if(root != NULL)
{
  InOrderTree(root->LChild);
  printf("%c  ",root->data);
  InOrderTree(root->RChild);
}
}
//递归法后序遍历二叉树
void PostOrderTree(BiTree root)
{
    if(root != NULL)
{
  PostOrderTree(root->LChild);
  PostOrderTree(root->RChild);
  printf("%c  ",root->data);
}
}

void main()
{
BiTree BT;
printf("请输入先序序列:");
CreateBiTree(&BT);
//BT = CreateBiTree();
    printf("\n递归方法实现如下:\n");
    printf("\n先序遍历结果为:");
PreOrderTree(BT);
printf("\n中序遍历结果为:");
InOrderTree(BT);
printf("\n后序遍历结果为:");
PostOrderTree(BT);
printf("\n");
}
该代码是我做过的一个实验,经过验证的,是采用递归算法的。如果有疑问,可以提
4#
ljlhyforever  1级新秀 | 2018-4-30 01:55:48 发帖IP地址来自
推荐你看一下严蔚敏的数据结构(C语言版)那里讲的很详细。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:
帖子:
精华:
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP