99网
您的当前位置:首页实验五 二叉树的创建和遍历

实验五 二叉树的创建和遍历

来源:99网


#include

#include

#include

#define maxsize 1024

typedef char datatype;

typedef struct node

{ datatype data;

struct node *lchild, * rchild;

} bitree;

bitree *CREATREE()

{ char ch;

bitree * Q [maxsize];

int front, rear;

bitree * root, *s;

root=NULL;

front=1;rear=0;

printf(\"请输入二叉树的各结点,@表示虚结点,#表示结束:\\n\");

scanf(\"%c\

while(ch!='#')

{ putchar(ch);

s=NULL;

if(ch!='@')

{ s=(bitree *)malloc(sizeof(bitree));

s->data=ch;

s->lchild=NULL;

s->rchild=NULL;

}

rear++;

Q[rear]=s;

if(rear==1) root=s;

else

{ if(s && Q[front])

if(rear%2==0) Q[front]->lchild=s;

else Q[front]->rchild=s;

if(rear % 2==1) front++;

}

scanf(\"%c\

}

return root;

}

void preorder(bitree *p)

{ if(p!=NULL)

{ printf(\"%c\

preorder(p->lchild);

preorder(p->rchild);

}

return;

}

void inorder(bitree *p)

{

if(p!=NULL)

{ inorder(p->lchild);

printf(\"%c\

inorder(p->rchild);

}

return;

}

void postorder (bitree *p)

{

if(p!=NULL)

{ postorder(p->lchild);

postorder(p->rchild);

printf(\"%c\

}

return;

}

void main()

{

bitree * root;

root=CREATREE();

printf(\"\\n先序遍历结果如下:\\n\");

preorder(root);

printf(\"\\n中序遍历结果如下:\\n\");

inorder(root);

printf(\"\\n后序遍历结果如下:\\n\");

postorder(root);

printf(\"\\n\");

}

因篇幅问题不能全部显示,请点此查看更多更全内容