建立并中序遍历一个排序二叉树
排序二叉树是指左子树的所有节点的值均小于它根节点的值,右子树的所有节点的值均大于它根节点的值,如下图是一棵排序二叉树
输入:
输入有一行,表示若干个要排序的数,输入0时停止
输出
二叉树的凹入表示
和二叉树的中序遍历序列
sample:
input:
56 78 34 89 12 35 67 77 22 57 0
output:
12
22
34
35
56
57
67
77
78
89
12 22 34 35 56 57 67 77 78 89
测试输入 | 期待的输出 | 时间限制 | 内存限制 | 额外进程 | |
---|---|---|---|---|---|
测试用例 1 | 以文本方式显示
| 以文本方式显示
| 无限制 | 64M | 0 |
测试用例 2 | 以文本方式显示
| 以文本方式显示
| 无限制 | 64M | 0 |
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int v,depth;
struct node *lc,*rc;
}tnode;
void buildtree(tnode* p,int i,int d)
{
d++;
if(i<p->v)
{
if(p->lc==NULL)
{
p->lc=(tnode*)malloc(sizeof(tnode));
p->lc->v=i;
p->lc->depth=d;
p->lc->lc=p->lc->rc=NULL;
return;
}
else
{
buildtree(p->lc,i,d);
}
}
else
{
if(p->rc==NULL)
{
p->rc=(tnode*)malloc(sizeof(tnode));
p->rc->v=i;
p->rc->depth=d;
p->rc->lc=p->rc->rc=NULL;
return;
}
else
{
buildtree(p->rc,i,d);
}
}
return;
}
void traverseinorder(tnode *p)
{
if(p==NULL) return;
traverseinorder(p->lc);
printf(" %d",p->v);
traverseinorder(p->rc);
return;
}
void concaveprint(tnode *p)
{
if(p==NULL) return;
concaveprint(p->lc);
for(int j=0;j<p->depth;++j) printf(" ");
printf("%d\n",p->v);
concaveprint(p->rc);
return;
}
int main(){
tnode *head;
int i;
scanf("%d",&i);
head=(tnode*)malloc(sizeof(tnode));
head->v=i;
head->depth=0;
head->lc=head->rc=NULL;
while(1)
{
scanf("%d",&i);
if(!i) break;
buildtree(head,i,0);
}
concaveprint(head);
printf("\n");
traverseinorder(head);
printf("\n");
}