二叉树的操作

来源:互联网 发布:交换机更换网络 编辑:程序博客网 时间:2024/04/30 03:00


包含根据广义表来创建二叉树,显示二叉树,先、中、后序访问二叉树


#include<stdio.h>#include<stdlib.h>#include<string.h>#define ElemType char#define uint unsigned int#define N 100typedef struct tree{ElemType data;struct tree *lchild,*rchild;}TreeNode;TreeNode *create( char tree[]);void showtree(TreeNode *);void preorder(TreeNode *head);void inorder(TreeNode *head);void postorder(TreeNode *head);int main(){TreeNode *head;char tree[100]="A(B(M,N),C(E))";//printf("input the string\n");//scanf("%s",tree);head=NULL;head=create(tree);showtree(head);printf("\n");preorder(head);printf("\n");inorder(head);postorder(head);return 0;}TreeNode *create( char tree[])    //新建树 {uint i=0,len;int flag=0,top=-1;len=strlen(tree);TreeNode *p,*st[N];for(i=0;i<len;i++){switch(tree[i]){case '(': top++; st[top]=p; flag=1;break;case ',': flag=2; break;case ')': top--; break;default:p=(TreeNode *)malloc(sizeof(TreeNode));p->data=tree[i];p->lchild=p->rchild=NULL;if(top==-1){top++;st[top]=p;}else{switch(flag){case 1: st[top]->lchild=p; break;case 2: st[top]->rchild=p; break;}}} }return st[0];}void showtree(TreeNode *head)   //显示树{if(head!=NULL){printf("%c",head->data);if(head->lchild!=NULL || head->rchild!=NULL){printf("(");showtree(head->lchild);if(head->rchild!=NULL)printf(",");showtree(head->rchild);printf(")");}}}void preorder(TreeNode *head)  //先序非递归遍历{TreeNode *st[N],*p=head;int top=-1;if(head!=NULL){top++;st[top]=head;while(top>-1){p=st[top];top--;printf("%c",p->data);if(p->rchild!=NULL){top++;st[top]=p->rchild;}if(p->lchild!=NULL){top++;st[top]=p->lchild;}}}}void inorder(TreeNode *head)  //中序非递归遍历{TreeNode *p,*st[N];int top=-1;if(head!=NULL){p=head;while(top>-1 || p!=NULL){while(p!=NULL){top++;st[top]=p;p=p->lchild;}if(top>-1){     printf("%c",st[top]->data);p=st[top]->rchild;top--;}}}printf("\n");}void postorder(TreeNode *head)  //后序非递归遍历{TreeNode *p,*st[N];int top=-1;if(head!=NULL){top++;st[top]=head;do{p=NULL;while(st[top]->lchild!=NULL){st[top+1]=st[top]->lchild;top++;}}while(top>-1);}}




0 0
原创粉丝点击