您的位置:首页 > 编程语言

二叉搜索树代码

2016-05-08 10:39 120 查看
#include<stdio.h>

#include<malloc.h>

#include<stdlib.h>

#define NULL 0

typedef struct node

{

    int data;

    struct node * lchild;

    struct node * rchild;

}Btree;

Btree*CreateBtree(int a[], int n)

{

    int i;

    Btree*root, *pb, *pa, *pc;

    root = (Btree*)malloc(sizeof(Btree));

    root->data = a[0];

    root->lchild = root->rchild = NULL;

    for (i = 1; i < n; i++)

    {

        pb = (Btree*)malloc(sizeof(Btree));

        pb->data = a[i];

        pb->lchild = pb->rchild = NULL;

        pc = root;

        while (pc)

        {

            pa = pc;

            if (pc->data > pb->data)  pc = pc->lchild;

            else pc = pc->rchild;

        }

        if (pa->data > pb->data)

            pa->lchild = pb;

        else pa->rchild = pb;

    }

    return root;

}

void PreOrder(Btree*root)

{

    if(root)

    {

       printf("%5d",root->data);

       PreOrder(root->lchild);

       PreOrder(root->rchild);

    }

}

void InOrder(Btree*root)

{

    if(root)

    {

        InOrder(root->lchild);

        printf("%5d",root->data);

        InOrder(root->rchild);

    }

}

void PostOrder(Btree*root)

{

    if(root)

    {

        PostOrder(root->lchild);

        PostOrder(root->rchild);

        printf("%5d",root->data);

    }

}

int CountNode(Btree*root)

{

    int cr,cl;

    if(root)

    {

        cr=CountNode(root->rchild);

        cl=CountNode(root->lchild);

    }

        return cr+cl+1;

}

int DepthTree(Btree*root)

{

    int dr,dl,d=0;

    if(root)

    {

        dr=DepthTree(root->rchild);

        dl=DepthTree(root->lchild);

        d=dl>dr?dl+1:dr+1;

    }

    return d;

}

void main()

{

    Btree*root = NULL;

    int a[] = { 5,3,1,7,6,4,8,2 },count=0,d=0;

    root = CreateBtree(a, 8);

    PreOrder(root);

    InOrder(root);

    PostOrder(root);

    

    count=CountNode(root);

    printf("%5d",count);

    d=DepthTree(root);

    printf("%5d",d);

    getchar();

}

   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: