Binary Search Tree analog

来源:互联网 发布:腾讯 大数据 排行 编辑:程序博客网 时间:2024/04/30 08:34

Input

The first integer of the input is T, the number of test cases.

Each test case has two lines.

The first line contain an integer N,(1<=N<=1000), the number of numbers need to be inserted into the BST.

The second line contain N integers separated by space, each integer is in the range of [0,230].

Output

Each test case, output must contain three lines: the preorder, inorder and postorder traversal sequence. The numbers in each line should be separated by a single space and you should not output anything at the end of the line! Output a blank line after each case.

Sample Input

153 6 9 5 1

Sample Output

3 1 6 5 91 3 5 6 91 5 9 6 3

HINT

#include <stdio.h>
#define N 1000
struct node
{
int x;
struct node *left,*right;
}node[N];
char f;
void Insert(struct node *r,struct node *p)
{
if(!r) return;
if(r->x>p->x)
{
if(r->left) Insert(r->left,p);
else r->left=p;
}
else
{
if(r->right) Insert(r->right,p);
else r->right=p;
}
}
void pretral(struct node *p)
{
if(!p) return;
if(f) printf("%d",p->x),f=0;
else printf(" %d",p->x);
pretral(p->left);
pretral(p->right);
}
void intral(struct node *p)
{
if(!p) return;
intral(p->left);
if(f) printf("%d",p->x),f=0;
else printf(" %d",p->x);
intral(p->right);
}
void postod(struct node *p)
{
if(!p) return;
postod(p->left);
postod(p->right);
if(f) printf("%d",p->x),f=0;
else printf(" %d",p->x);
}
int main()
{
int t,i,n,x;
struct node root;
struct node *p;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
scanf("%d",&root.x);
root.left=root.right=0;
for(i=0;i<n-1;i++)
{
scanf("%d",&x);
p=&node[i];
p->x=x;
p->left=p->right=0;
Insert(&root,p);
}
f=1;
pretral(&root);
printf("\n");
f=1;
intral(&root);
printf("\n");
f=1;
postod(&root);
printf("\n");
printf("\n");
}
return 0;
}


0 0