中序遍历二叉排序树
输入一整数序列,建立二叉排序树,然后中序遍历。
输入第一行为整数的个数n,第二行是具体的n个整数。
建立二叉排序树,然后输出中序遍历的结果。
输入示例:
5
1 6 5 9 8
输出:
1 5 6 8 9
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct stu{ int data; struct stu *lc,*rc; }bitree; bitree *creat(int n){ int ch; bitree *q[100];//设置指针型数组构建队列 int front,rear; int num=0,i; bitree *root,*s,*p; root=NULL; front=1,rear=0; while(num<n){ s=NULL; scanf("%d",&ch); s=(bitree*)malloc(sizeof(bitree)); s->data=ch; s->lc=NULL; s->rc=NULL; rear++; q[rear]=s; if(rear==1)root=s; else{ p=q[1]; while(1){ if(s->data>p->data&&p->rc!=NULL) { p=p->rc; } if(s->data>p->data&&p->rc==NULL){ p->rc=s; break; } if(s->data<p->data&&p->lc!=NULL){ p=p->lc; } if(s->data<p->data&&p->lc==NULL){ p->lc=s; break; } } }//建立二叉排序树 num++; } return root; }//建立二叉树 void order(bitree *root){ if(root!=NULL){ order(root->lc);//递归 printf("%d ",root->data); order(root->rc); } }//中序遍历二叉树 int main() { int n; bitree *root; scanf("%d",&n); fflush(stdin); root=creat(n); order(root); return 0; }
原文:https://www.cnblogs.com/wabulabudabuda/p/12853782.html