您的位置:首页 > 其它

Binary Search Tree analog

2015-06-25 01:07 267 查看

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

1
5
3 6 9 5 1

Sample Output

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

HINT

#include <stdio.h>

#define N 1000

struct node

{

int x;

struct node *left,*right;

}node
;

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;

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: