数据结构二叉树(实训报告)
#include<stdio.h> #include<stdlib.h> typedef char TElemType; typedef struct node{ TElemType data; //结点数据 struct node *lchild,*rchild; //左右子女指针 }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; //否则建立空子树 }; //以广义表的形式输出二叉树 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 Nodenum(BinTNode *T){ if(T == NULL){ return 0; }else{ return 1+Nodenum(T->lchild)+Nodenum(T->rchild); } } //计算二叉树的高度 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; } } //二叉树的叶子结点数 int Leafnum (BinTNode *T){ if(!T){ return 0; }else if((T->lchild == NULL)&&(T->rchild == NULL)){ return 1; }else { return (Leafnum (T->lchild)+Leafnum (T->rchild)); } } //输入结点找双亲结点 BinTNode *getParent (BinTNode *T,TElemType key){ if((T->lchild!=NULL&&T->lchild->data==key)||(T->rchild!=NULL)&&T->rchild->data==key){ return T; }else { getParent(T->lchild,key); getParent(T->rchild,key); } return NULL; } //输入结点找左孩子和右孩子结点 BinTNode *getNodenum(BinTNode *T,TElemType key){ if(T != NULL&&T->data == key){ return T; }else { getNodenum (T->lchild,key); getNodenum (T->rchild,key); } return NULL; } main(){ BinTree T; BinTree Parent,leftChild,rightChild; char key; BinTree Temp; char a[100]={'A','B','C','#','#','D','E','#','#','#','F','#','#',';'}; int i=0; createBinTree_Pre(T,a,i); printf("二叉树用广义表表示为:"); PrintBinTree(T); printf("\n二叉树的高度为:%d",Height(T)); printf("\n二叉树的总结点为:%d",Nodenum(T)); printf("\n二叉树的叶子结点为:%d",Leafnum(T)); printf("\n请输入需要查找的双亲结点的结点:"); scanf("%c",&key); getchar(); Parent = getParent(T,key); printf("输入的节点的双亲点的数据是:%c\n",Parent->data); printf("请输入需要查找左右孩子结点的结点:"); scanf("%c",&key); getchar(); Temp = getNodenum(T,key); leftChild = Temp->lchild; rightChild = Temp->rchild; printf("您输入的节点的左孩子节点数据是:%c\n",leftChild->data); printf("您输入的节点的右孩子节点数据是:%c\n",rightChild->data); }