树的建立和遍历

时间:2021-06-29 11:22:44

这段代码实现了二叉树的建立和前序、中序、后序、层序四种输出顺序

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
using namespace std;
struct tree
{
int data;
struct tree *l,*r;
};
void creatTree(int a,struct tree * &t);
void preorder(struct tree *t);
void inorder(struct tree *t);
void postorder(struct tree *t);
void layerorder(struct tree *t);
int main()
{
int n,order;
struct tree *root;
root=NULL;
printf("the amount of node:\n");
scanf("%d",&n);
printf("data:\n");
for(int i=0;i<n;i++)
{
int num;
scanf("%d",&num);
creatTree(num,root);
}
while(1)
{
printf("which order do you want to choose\n");
printf("1.preorder 2.inorder 3.postorder 4.layerorder 5.exit\n");
scanf("%d",&order);
switch(order)
{
case 1:
{
preorder(root);
putchar('\n');
break;
}
case 2:
{
inorder(root);
putchar('\n');
break;
}
case 3:
{
postorder(root);
putchar('\n');
break;
}
case 4:
{
layerorder(root);
putchar('\n');
break;
}
case 5:
exit(0);
}
}
return 0;
}
void creatTree(int a,struct tree * &t)
{
if(t==NULL)
{
struct tree *Node=new struct tree;
Node->data=a;
Node->l=NULL;
Node->r=NULL;
t=Node;
return ;
}
if(a<t->data)
{
creatTree(a,t->l);
}
else if(a==t->data)
{
return ;
}
else if(a>t->data)
{
creatTree(a,t->r);
}
}
void preorder(struct tree *t)
{
if(t==NULL)
return ;
printf("%d ",t->data);
preorder(t->l);
preorder(t->r);
}
void inorder(struct tree *t)
{
if(t==NULL)
return ;
inorder(t->l);
printf("%d ",t->data);
inorder(t->r);
}
void postorder(struct tree *t)
{
if(t==NULL)
return ;
postorder(t->l);
postorder(t->r);
printf("%d ",t->data);
}
void layerorder(struct tree *t)
{
queue<struct tree*> q;
q.push(t);
while(!q.empty())
{
printf("%d ",q.front()->data);
if(q.front()->l!=NULL)
q.push(q.front()->l);
if(q.front()->r!=NULL)
q.push(q.front()->r);
q.pop();
}
}