首页 > 编程语言 > 详细

C语言数据结构入门记——二叉排序树的建立

时间:2020-05-09 01:17:42      阅读:79      评论:0      收藏:0      [点我收藏+]

中序遍历二叉排序树

输入一整数序列,建立二叉排序树,然后中序遍历。

输入第一行为整数的个数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;
}

 

技术分享图片

C语言数据结构入门记——二叉排序树的建立

原文:https://www.cnblogs.com/wabulabudabuda/p/12853782.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!