设为首页 加入收藏

TOP

算法导论-二叉排序树(六)
2012-11-17 09:26:13 来源: 作者: 【 】 浏览:2468
Tags:算法 导论 排序

 

    三、代码清单

    [cpp]

    #include<stdio.h>

    #include<stdlib.h>

    #define maxSize 20

    #define maxWidth 20

    typedef int KeyType; //假定关键字类型为整数

    typedef struct node { //结点类型

    KeyType key; //关键字项

    struct node *lchild,*rchild;//左右孩子指针

    } BSTNode,BSTree;

    //typedef BSTNode *BSTree; //BSTree是二叉排序树的类型

    //先序遍历

    void preOrder(BSTree *BT)

    {

    if(BT!= NULL)

    {

    printf("%d",BT->key);

    preOrder(BT->lchild);

    preOrder(BT->rchild);

    }

    }

    //中序遍历

    void inOrder(BSTree *BT)

    {

    if(BT!= NULL)

    {

    inOrder(BT->lchild);

    printf("%d",BT->key);

    inOrder(BT->rchild);

    }

    }

    //后序遍历

    void postOrder(BSTree *BT)

    {

    if(BT!= NULL)

    {

    postOrder(BT->lchild);

    postOrder(BT->rchild);

    printf("%d",BT->key);

    }

    }

    //层次法打印树

    void dispTree(BSTree *BT)

    {

    BSTree *stack[maxSize],*p;

    int level[maxSize] ,top,n,i,width=4;

    if(BT!=NULL)

    {

    printf("Display a tree by hollow means.\n");

    top=1;

    stack[top]=BT;//push root point to stack.

    level[top][0]=width;

    while(top>0)

    {

    p=stack[top];

    n=level[top][0];

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

    printf(" ");

    printf("%d",p->key);

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

    printf("--");

    printf("\n");

    top--;

    if(p->rchild!=NULL)

    {

    top++;

    stack[top]=p->rchild;

    level[top][0]=n+width;

    level[top] =2;

    }

    if(p->lchild!=NULL)

    {

    top++;

    stack[top]=p->lchild;

    level[top][0]=n+width;

    level[top] =1;

    }

    }

    }

    }

    /* 向二叉排序树中加入一个结点

    要改变指针,需要传递指针的指针*/

    int InsertNode(BSTree **tree, KeyType key)

    {

    BSTNode *p= NULL, *parent = NULL;

    BSTNode *pNewNode = (BSTNode *)malloc(sizeof(BSTNode));

    if (pNewNode==NULL)

    {

    return -1;

    }

            

首页 上一页 3 4 5 6 7 8 下一页 尾页 6/8/8
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇求区间内小于num的数的个数 下一篇C++中私有继承和公有继承的特点

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: