数据结构(C语言描述)

Python014

数据结构(C语言描述),第1张

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

#define DataType int

#define MAXSIZE 1000

typedef struct node{

    DataType data

    struct node *lchild

    struct node *rchild

}BiTreeNode

DataType BT[MAXSIZE]

BiTreeNode* BuildBTree(DataType BT[], int n, int i)

{

    BiTreeNode * node

    if(i>=n || (node=(BiTreeNode*)malloc(sizeof(BiTreeNode)))==NULL) return NULL

    node->data = BT[i]

    node->lchild =  BuildBTree(BT, n, 2*i+1)

    node->rchild =  BuildBTree(BT, n, 2*i+2)

    return node

}

void PrintLevel(BiTreeNode * bt, int level, int l)

{

    if(!bt) return

    if(l < level)

        PrintLevel(bt->lchild, level,l+1)

    if(l == level)

        printf("%4d",bt->data)

    if(l < level)

        PrintLevel(bt->rchild, level,l+1)    

}

/* 先序凹入表示法输出, 一般通过前导的空格来凹入 #*/

/*pre,sur分别为前导后续字符,一般前导为空格字符,#*/

void PrintTree(BiTreeNode *bt,char pre,char sur,int depth,int level){

    if(bt==NULL) return  /*如果为空树,return;*/

    int i=0  /*先序输出根*/

    while(++i<level) printf("%c%c%c%c",pre,pre,pre,pre)   // 凹入,输出前导字符

    printf("%4d",bt->data)                // 输出当前节点

    while(i++<depth) printf("%c%c%c%c",sur,sur,sur,sur)    // 输出后续字符

    printf("\n")

    /*输出子树*/

    PrintTree(bt->lchild,pre,sur,depth,level+1)

    PrintTree(bt->rchild,pre,sur,depth,level+1)

}

void CTBT(int n)

{   // 建立初始n个节点的完全二叉树

    while(n--) BT[n] = n

}

int main()

{

    int i,n,depth

    BiTreeNode *bt

    scanf("%d",&n)

    CTBT(n)

    bt = BuildBTree(BT, n, 0)

    depth = (int)(log(n)/log(2))+1

    i=0

    while(++i<=depth)

    {

  printf("\nThe %dth Level:",i)

        PrintLevel(bt, i,1)

    }

 printf("\n")

    PrintTree(bt,' ','-',depth,1)

 return 0

}

经调试这个没问题,完成了要求的三个功能

1、线性数据结构

元素之间一般存在元素之间存在一对一关系,是最常用的一类数据结构,典型的有:数组、栈、队列和线性表。

2、树形结构

结点间具有层次关系,每一层的一个结点能且只能和上一层的一个结点相关,但同时可以和下一层的多个结点相关,称为“一对多”关系,常见类型有:树、堆。

3、图形结构

在图形结构中,允许多个结点之间相关,称为“多对多”关系。

(1)线性数据结构:元素之间一般存在元素之间存在一对一关系,是最常用的一类数据结构,典型的有:数组、栈、队列和线性表

(2)树形结构:结点间具有层次关系,每一层的一个结点能且只能和上一层的一个结点相关,但同时可以和下一层的多个结点相关,称为“一对多”关系,常见类型有:树、堆

(3)图形结构:在图形结构中,允许多个结点之间相关,称为“多对多”关系