樹結構練習——排序二叉樹的中序遍歷
Time Limit: 1000ms Memory limit: 65536K 有疑問?點這裏^_^
題目描述
輸入
輸出
示例輸入
1 2 2 1 20
示例輸出
2 1 20
提示
來源
示例程序
- #include<stdio.h>
- #include<string.h>
- #include<stdlib.h>
- struct node
- {
- int data;
- struct node *l, *r;
- };
- int cnt;
- int n;
- struct node *build(struct node *&tree, int a)
- {
- if(tree==NULL)
- {
- tree=new node;
- tree->l=NULL;
- tree->r=NULL;
- tree->data=a;
- }
- else
- {
- if(a<tree->data)
- build(tree->l, a);
- else
- build(tree->r, a);
- }
- return tree;
- };
- void mid(struct node *tree)
- {
- if(tree)
- {
- mid(tree->l);
- if(cnt==1)
- {
- printf("%d", tree->data);
- cnt++;
- }
- else
- {
- printf(" %d", tree->data);
- }
- mid(tree->r);
- }
- }
- int main()
- {
- int n, x;
- while(~scanf("%d", &n))
- {
- cnt=1;
- struct node *tree=NULL;
- for(int i=0;i<n;i++)
- {
- scanf("%d", &x);
- build(tree, x);
- }
- mid(tree);
- printf("\n");
- }
- return 0;
- }