数据结构树(二叉树的使用)
#include<stdio.h> #include<stdlib.h> #define maxSize 127 typedef char TElemType; typedef struct node{ TElemType data; //结点数据 struct node *lchild,*rchild; //左右子女指针 int length; }BinTNode, *BinTree; //二叉树定义 //创建二叉树 void createBinTree_Pre(BinTNode *T,TElemType pre[],int &n){ TElemType ch = pre[n++]; if(ch == ';') return; if(ch != '#'){ T = (BinTNode*) malloc (sizeof(BinTNode)); //递归根节点 T->data=ch; createBinTree_Pre(T->lchild,pre,n); //递归建立左子树 createBinTree_Pre(T->rchild,pre,n); //递归建立右子树 }else T = NULL; //否则建立空子树 T->length=n; }; //以广义表的形式输出二叉树 void PrintBinTree (BinTNode *T){ if(T!=NULL){ printf("%c",T->data); if(T->lchild!=NULL||T->rchild!=NULL){ printf("("); PrintBinTree(T->lchild); printf(","); PrintBinTree(T->rchild); printf(")"); } } } //计算二叉树的高度 int Height(BinTNode *T){ if(T==NULL) return 0; //递归结束:空树高度为0 else { int i = Height(T->lchild); int j = Height(T->rchild); return (i < j)?j+1:i+1; } } main(){ BinTNode T; char a[7]={'A','B','C','D','#','#',';'}; int i=0,j; createBinTree_Pre(&T,a,i); PrintBinTree(&T); j=Height(&T); printf("二叉树的高度为%d",j); }