二叉树链式存储的C实现

来源:互联网 发布:手机淘宝关闭智能联想 编辑:程序博客网 时间:2024/05/18 12:32

在实现二叉树的链式存储的过程中,我遇到了一些问题,感到对递归的理解还不够深入。另外,代码中有一处必须使用全局变量做数组索引,还在研究其中的原因,代码已完成,现在贴在博客中供参考

#include<stdio.h>#include<stdlib.h>#include<string.h>#include<time.h>#define MAXSIZE 100#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0typedef int Status;typedef int TElemType;typedef char String[MAXSIZE];typedef struct BiTreeNode{    TElemType data;    struct BiTreeNode * lchild;    struct BiTreeNode * rchild;}BiTreeNode;typedef struct BiTreeNode * BiTree;String str;int i=1;/*此处必须要用全局变量做索引,暂时不知为何*//*对字符串进行赋值*/ Status AssignString(String S,char * chars){    int i=0;    if(strlen(chars)>MAXSIZE)        return ERROR;    else{        S[0]=strlen(chars);        for(i=1;i<=S[0];i++)            S[i]=*(chars+i-1);    }    return OK;}Status Visit(TElemType c){    printf("%c",c);    return OK;}/*初始化二叉树*/ Status InitBiTree(BiTree *T){    (*T)=NULL;    return OK;}/*创建二叉树*/ Status CreateBiTree(BiTree *T){    TElemType data;    data=str[i++];    if(data=='#')        *T=NULL;    else{        *T=(BiTree)malloc(sizeof(BiTreeNode));        if(!(*T))           return ERROR;        (*T)->data=data;        CreateBiTree(&(*T)->lchild);/*递归建立左子树*/         CreateBiTree(&(*T)->rchild);/*递归建立右子树*/     }}/*判断是否为空树*/ Status EmptyBiTree(BiTree T){    if(!T)       return TRUE;    else       return FALSE;}/*求树的深度*/ Status DepthBiTree(BiTree T){    int i,j;    if(!T)       return ERROR;    else{        if(T->lchild)           i=DepthBiTree(T->lchild);        else           i=0;        if(T->rchild)           j=DepthBiTree(T->rchild);        else           j=0;    }    return i>j? i+1:j+1;}/*返回根节点*/ Status Root(BiTree T){    return T->data;}/*销毁二叉树*/ Status DestroyBiTree(BiTree * T){    if(!T)       return ERROR;    else{        if((*T)->lchild)        DestroyBiTree(&(*T)->lchild);/*递归销毁左子树*/         if((*T)->rchild)        DestroyBiTree(&(*T)->rchild);/*递归销毁右子树*/     }    free(*T);    *T=NULL;/*free后指向空*/ }/*前序遍历*/ Status Preorder(BiTree T){    if(!T)        return ERROR;    Visit(T->data);    Preorder(T->lchild);    Preorder(T->rchild);    return OK;}/*中序遍历*/ Status Inorder(BiTree T){    if(!T)       return ERROR;    Inorder(T->lchild);    Visit(T->data);    Inorder(T->rchild);    return OK;}/*后序遍历*/ Status Lastorder(BiTree T){    if(!T)       return ERROR;    Lastorder(T->lchild);    Lastorder(T->rchild);    Visit(T->data);    return OK;}int main(void){    BiTree T;    AssignString(str,"ABDH#K###E##CFI###G#J##");//  for(int i=1;i<=str[0];i++)//     printf("%c ",str[i]);    InitBiTree(&T);    CreateBiTree(&T);    printf("构造空二叉树后,树空否?%d(1:是 0:否) 树的深度=%d\n",EmptyBiTree(T),DepthBiTree(T));    printf("二叉树的根为: %c\n",Root(T));    printf("\n前序遍历二叉树:");    Preorder(T);    printf("\n中序遍历二叉树:");    Inorder(T);    printf("\n后序遍历二叉树:");    Lastorder(T);    DestroyBiTree(&T);    printf("\n清除二叉树后,树空否?%d(1:是 0:否) 树的深度=%d\n",EmptyBiTree(T),DepthBiTree(T));}
0 0
原创粉丝点击