/*
输入一系列整数,建立二叉排序数,并进行前序,中序,后序遍历
*/
#include <stdio.h>
#include <iostream>
using namespace std;
struct Node{
Node *lchild;
Node *rchild;
int c;
}Tree[110];
int loc;
Node *creat(){
Tree[loc].lchild=Tree[loc].rchild=NULL;
return &Tree[loc++];
}
void postOrder(Node *T){
if (T->lchild!=NULL)
postOrder(T->lchild);
if (T->rchild!=NULL)
postOrder(T->rchild);
printf("%-3d",T->c);
}
void inOrder(Node *T){
if (T->lchild!=NULL)
postOrder(T->lchild);
printf("%-3d",T->c);
if (T->rchild!=NULL)
inOrder(T->rchild);
}
void preOrder(Node *T){
printf("%-3d",T->c);
if (T->lchild!=NULL)
postOrder(T->lchild);
if (T->rchild!=NULL)
preOrder(T->rchild);
}
Node *Insert(Node *T,int x){
if (T==NULL) {
T=creat();
T->c=x;
return T;
}
else if(x<T->c)
T->lchild=Insert(T->lchild, x);
else if(x>T->c)
T->rchild=Insert(T->rchild, x);
return T;
}
int AVLTree(){
int n;
Node *T = NULL;
while (scanf("%d",&n)!=EOF) {
for (int i=0; i<n; i++) {
int x;
cin>>x;
T=Insert(T,x);
}
preOrder(T);
putchar('\n');
inOrder(T);
putchar('\n');
postOrder(T);
putchar('\n');
}
return 0;
}
二叉排序树遍历
最新推荐文章于 2023-06-07 22:56:29 发布