二叉树的建立与输出以及其他一些相关操作(递归算法实现) C语言

来源:互联网 发布:忆典网络机顶盒打不开 编辑:程序博客网 时间:2024/05/16 23:40
/********************************************************/#include <stdio.h>#include <stdlib.h>#include <malloc.h>/********************************************************/#define OK1#defineERROR0#defineTRUE1#defineFALSE0typedefcharElemType;//数据类型typedefintStatus;//返回值类型/********************************************************/typedef struct BiTNode{ElemTypedata;//数据域struct BiTNode*lChild, *rChlid;//左右子树域}BiTNode, *BiTree;/********************************************************///先序创建二叉树Status CreateBiTree(BiTree *T){ElemType ch;ElemType temp;scanf("%c", &ch);temp = getchar();if (' ' == ch)*T = NULL;else{*T = (BiTree)malloc(sizeof(BiTNode));if (!(*T))exit(-1);(*T)->data = ch;printf("输入%c的左子节点:", ch);CreateBiTree(&(*T)->lChild);printf("输入%c的右子节点:", ch);CreateBiTree(&(*T)->rChlid);}return OK;}/********************************************************///先序遍历二叉树void TraverseBiTree(BiTree T){if (NULL == T)return ;printf("%c ", T->data);TraverseBiTree(T->lChild);TraverseBiTree(T->rChlid);}/********************************************************///二叉树的输出 嵌套括号表示法void DispBiTree(BiTree T){if (NULL != T){printf("%c", T->data);if (T->lChild!=NULL || T->rChlid!=NULL){printf("(");DispBiTree(T->lChild);if (NULL != T->rChlid)printf(",");DispBiTree(T->rChlid);printf(")");}}}/*********************************************************///二叉树的输出 凹入表表示法 输出无法分辨左右子数//写的不好 第一次调用时必须给一个参数i  用来控制空格的数目void DispBiTree_into(BiTree T, int i){int k = i;if (NULL != T){putchar('\n');while (k){putchar(' ');--k;}printf(" %c", T->data);DispBiTree_into(T->lChild, i+1);DispBiTree_into(T->rChlid, i+1);}}/********************************************************///查找结点 如果找到就返回指向该结点的指针 否则返回NULLBiTree locate(BiTree T, ElemType e){BiTree p;if (NULL == T)return NULL; else{if (e == T->data)return T;elsep = locate(T->lChild, e);if (p)return p;elsereturn locate(T->rChlid, e);}}/********************************************************///统计树中结点的个数int numofnode(BiTree T){if (NULL == T)return 0;elsereturn (numofnode(T->lChild) + numofnode(T->rChlid) + 1);}/********************************************************///判断二叉树是否等价Status isequal(BiTree T1, BiTree T2){int t = 0;if (NULL==T1 && NULL==T2)t = 1;else{if (T1!=NULL && T2!=NULL)//如果两棵树都不为空if (T1->data == T2->data)//根节点相同if ( isequal(T1->lChild, T2->lChild) )//如果左子树相同 就继续比较右子树  t = isequal(T1->rChlid, T2->rChlid);}return t;}/********************************************************///求二叉树的高度int depth(BiTree T){int h, lh, rh;if (NULL == T)h = 0;else{lh = depth(T->lChild);rh = depth(T->rChlid);if (lh >= rh)h = lh+1;elseh = rh+1;}return h;}/********************************************************/int main(void){BiTree T;BiTree p;int i=0;CreateBiTree(&T);TraverseBiTree(T);DispBiTree(T);DispBiTree_into(T, i);p = locate(T, 'c');printf("\n\n%c\n", p->data);i = numofnode(T); printf("%d", i);return 0;}


 

原创粉丝点击