本人数据结构实验课写出来的垃圾代码。仅供参考。
树的应用
1、实验目的
通过本实验掌握二叉的建立和递归遍历、非递归遍历算法,了解二叉树在实际中的应用并熟练运用二叉树解决实际问题。
2、实验内容
根据前序遍历的顺序建立一棵二叉树,并根据遍历规则遍历二叉树。并打印输出。
3、实验要求
(1)根据前序遍历的顺序创建一棵二叉树;
(2)对二叉树进行前序、中序、后序遍历。
代码:
#include"stdio.h"
#include"stdlib.h"
typedef struct bintnode{
char data;
struct bintnode *lchild,*rchild;
}node;//樹結構
typedef node *binepoint;
typedef struct seqstack{
binepoint data[100];
int tag[100];
int top;
}stack;//棧結構
void push(stack *s,binepoint t)
{
s->data[s->top]=t;
s->top++;
}//壓棧函數
binepoint pop(stack *s)
{
if(s->top!=0)
{
s->top--;
return (s->data[s->top]);
}
else return NULL;
}//出棧函數
int main()
{
binepoint createtree();
void preorder(binepoint t);
void inorder(binepoint t);
void postorder(binepoint t);
void preorder1(binepoint t);
void inorder1(binepoint t);
void postorder1(binepoint t);
node *root;
root=createtree();
printf("首先。這個是前序遍曆\n");
preorder(root);
putchar('\n');
preorder1(root);
putchar('\n');
printf("第二。我們要進行中序遍歷\n");
inorder(root);
putchar('\n');
inorder1(root);
putchar('\n');
printf("最後,我們要進行後序遍曆\n");
postorder(root);
putchar('\n');
postorder(root);
putchar('\n');
return 0;
}
binepoint createtree()
{
char ch;
binepoint t;
if ((ch=getchar())=='#') t=NULL;
else {
t=(node*)malloc(sizeof(node));
t->data=ch;
t->lchild=createtree();
t->rchild=createtree();
}
return t;
}
void preorder(binepoint t)
{
stack s;
s.top=0;
while((t||(s.top!=0)))
{
if(t)
{
printf("%c",t->data);
push(&s,t);
t=t->lchild;
}
else
{
t=pop(&s);
t=t->rchild;
}
}
}
void inorder(binepoint t)
{
stack s;
s.top=0;
while((t!=NULL)||(s.top!=0))
{
if(t)
{
push(&s,t);
t=t->lchild;
}
else
{
t=pop(&s);
printf("%c",t->data);
t=t->rchild;
}
}
}
void postorder(binepoint t)
{
stack s;
s.top=0;
while((t)||(s.top!=0))
{
if(t)
{
s.data[s.top]=t;
s.tag[s.top]=0;
s.top++;
t=t->lchild;
}
else if(s.tag[s.top-1]==1)
{
s.top--;
t=s.data[s.top];
printf("%c",t->data);
t=NULL;
}
else
{
t=s.data[s.top-1];
s.tag[s.top-1]=1;
t=t->rchild;
}
}
}
void preorder1(binepoint t)
{
if (t)
{
printf("%c",t->data);
preorder1(t->lchild);
preorder1(t->rchild);
}
}
void inorder1(binepoint t)
{
if(t)
{
inorder1(t->lchild);
printf("%c",t->data);
inorder1(t->rchild);
}
}
void postorder1(binepoint t)
{
if(t)
{
postorder1(t->lchild);
postorder1(t->rchild);
printf("%c",t->data);
}
}