先序,中序,后序遍历

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define ARRAYLEN 10
int source[]={54,90,6,69,12,37,92,28,65,83};
typedef struct bst
{
    int data;
    struct bst *left;
    struct bst *right;
}BSTree;
BSTree bst,*pos;
void InsertBST(BSTree *t,int key)
{
    BSTree *p,*parent,*head;
    if(!(p=(BSTree*)malloc(sizeof(BSTree))))
    {
        printf("shenqingshibai");
        exit(0);
    }
    p->data=key;//新建p节点来保存数据 ,为31~34行赋值做准备 
    p->left=p->right=NULL;//新加的节点必定是叶子节点,没有孩子 
    head=t;
    while(head)
    {
        parent=head;
        if(key<head->data)
            head=head->left;
        else
            head=head->right;
    }
    if(key<parent->data)
        parent->left=p;
    else
        parent->right=p;
}


void CreateBST(BSTree *t,int data[],int n)
{
    int i;
    t->data=data[0];//为根节点赋值 ,data[0]即为主函数中source[0] 
    t->left=t->right=NULL;
    for(i=0;i<n;i++)
    {
        InsertBST(t,data[i]);
    }
}



BSTree *SearchBST(BSTree *t,int key)
{
    if(!t||t->data==key)
        return t;
    else if(key>t->data)
        return(SearchBST(t->right,key));
    else 
        return(SearchBST(t->left,key));
} 

void DLR(BSTree *t)
{
    if(t)
    {
        //if(t==&bst)  
            printf("%d ",t->data);
        //else  
            //printf(" ");  
        DLR(t->left);
        DLR(t->right);
    }
    return;
}



void LDR(BSTree *t)
{
    if(t)
    {
        LDR(t->left);
        //if(t==&bst)  
            printf("%d ",t->data); 
        //else  
            //printf(" ");
        LDR(t->right);
    }
    return;
}




void LRD(BSTree *t)
{
    if(t)
    {
        LDR(t->left);
        LDR(t->right); 
        //if(t==&bst)  
            printf("%d ",t->data);  
        //else  
            //printf(" "); 
    }
    return;
}


int main()
{
    int key;
    CreateBST(&bst,source,ARRAYLEN);
    printf("先序遍历:"); 
    DLR(&bst);
    printf("\n");
    printf("中序遍历:"); 
    LDR(&bst);
    printf("\n");
    printf("后序遍历:");
    LRD(&bst);
    printf("\n请输入关键字:");
    scanf("%d",&key);
    pos=SearchBST(&bst,key);
    if(pos)
        printf("查找成功,该节点地址为:%x\n",pos);
    else
        printf("查找失败\n"); 
    getch();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值