二叉树

来源:互联网 发布:编程入门先学什么语言 编辑:程序博客网 时间:2024/06/04 01:15
#include<stdio.h>#include<malloc.h>typedef struct Node{char data;struct Node *lchild;struct Node *rchild;}BiTreeNode;BiTreeNode *CreatBiTree(BiTreeNode *t,char *s)//二叉树的创建{BiTreeNode *p[1024];BiTreeNode *q=NULL;int top=0;int i=0,j,len=0;char ch;ch=s[i];while(ch!='\0'){switch(ch){case '(':top++;p[top]=q;j=1;break;case ')':top--;break;case ',':j=2;break;default:q=(BiTreeNode *)malloc(sizeof(BiTreeNode));q->data=ch;q->lchild=q->rchild=NULL;if(t==NULL)t=q;else{switch(j){case 1:p[top]->lchild=q;break;case 2:p[top]->rchild=q;break;}}}i++;ch=s[i];}return t;}void PreOrder(BiTreeNode *t)//先序遍历{if(t!=NULL){printf("%c ",t->data);PreOrder(t->lchild);PreOrder(t->rchild);}}void InOrder(BiTreeNode *t)//中序遍历{if(t!=NULL){PreOrder(t->lchild);printf("%c ",t->data);PreOrder(t->rchild);}}void PostOrder(BiTreeNode *t)//后序遍历{if(t!=NULL){PreOrder(t->lchild);PreOrder(t->rchild);printf("%c ",t->data);}}int BiTreeDepth(BiTreeNode *t){    int dep=0,depl,depr;    if(!t)dep=0;    else{depl=BiTreeDepth(t->lchild);depr=BiTreeDepth(t->rchild);dep=1+(depl>depr?depl:depr);}    return dep;}void main(){BiTreeNode *t=NULL;char *s="a(b(d,e),c)";t=CreatBiTree(t,s);printf("先序遍历:");PreOrder(t);printf("\n");printf("中序遍历:");InOrder(t);printf("\n");printf("后序遍历:");PostOrder(t);printf("\n");printf("二叉树深度为%d\n",BiTreeDepth(t));system("pause");}

原创粉丝点击