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 traversalsequence. 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;
}
相关文章推荐
- 关于CocosPods的安装和配置ReactiveCocoa
- Kidding_wjj
- 地址栏参数特殊字符
- 简单Ajax例子
- free(p)后指针问题
- jquery 全选 反选 取消 批量删除
- 各级(省市县镇村)行政区域获取
- [LeetCode] Word Ladder
- iframe+dialog实现对话框为iframe
- LVS-Web基础构架:负载均衡和LVS
- LVS-【大型网站技术实践】初级篇:借助LVS+Keepalived实现负载均衡
- Android 存储数据SharedPreferences详解
- Launchpad图标出错,恢复Launchpad
- windows下wamp使用须知
- android--超级手电筒的开发记录
- VS2015 错误 C4996 'fopen': This function or variable may be unsafe.
- Linux操作系统配置maven
- 优化SqlServer--数据压缩
- Project Seasons Work In Progress 4
- linux下mysql的远程连接