二叉树的链式存储结构

来源:互联网 发布:node.js与java 编辑:程序博客网 时间:2024/05/18 16:15

基本步骤:

①、二叉树的链式存储结构;

②、编写创建二叉树、输出二叉树的算法;

③、编写后序遍历递归算法;

④、编写中序遍历递归算法;

⑤、编写先序遍历递归算法;

⑥、编写先序遍历非递归算法;

⑦、编写中序遍历非递归算法;

⑧、编写后序遍历非递归算法;

⑨、编写主函数。

代码如下:

#include<stdio.h>#include<stdlib.h>#include<malloc.h>#include<iostream>#define Maxsize 50#define MaxSize 50#define NULL 0 //①二叉树的链式存储结构;typedef char ElemType;typedef struct node{    ElemType data;struct node *lchild;struct node *rchild;} BTNode; //②、编写创建二叉树、输出二叉树的算法;void CreateBTNode(BTNode * &b,char *str)  //创建二叉树{BTNode *St[Maxsize],*p=NULL;int top=-1,k,j=0;char ch;b=NULL;ch=str[j];while(ch!='\0'){switch(ch){case '(' :top++;St[top]=p;k=1;break;case ')' :top--;break;case ',' :k=2;break; default:p=(BTNode *)malloc(sizeof(BTNode));p->data=ch;p->lchild=p->rchild=NULL;if(b==NULL)b=p;else{switch(k){case 1:St[top]->lchild=p;break;case 2:St[top]->rchild=p;break;}}}j++;ch=str[j];}}void DispBTNode(BTNode *b)    //输出二叉树{if (b!=NULL){       printf("%c",b->data);   if(b->lchild!=NULL || b->rchild!=NULL)   {   printf("(");   DispBTNode(b->lchild);   if(b->rchild!=NULL)   printf(",");   DispBTNode(b->rchild);   printf(")");   }}}//③、编写后序遍历递归算法;void PostOrder(BTNode *b)  {  if (b!=NULL)      {  PostOrder(b->lchild); PostOrder(b->rchild); printf("%c ",b->data);     } }//④、编写中序遍历递归算法;void InOrder(BTNode *b) {  if (b!=NULL)      {  InOrder(b->lchild); printf("%c ",b->data);  InOrder(b->rchild);    } }//⑤、编写先序遍历递归算法;void PreOrder(BTNode *b)    {  if (b!=NULL)         {  printf("%c ",b->data);     PreOrder(b->lchild);    PreOrder(b->rchild);       }  }//⑥、编写先序遍历非递归算法;void PreOrder1(BTNode *b){BTNode *St[MaxSize],*p;int top = -1;top++;St[top]=b;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 InOrder1(BTNode *b){  BTNode *St[MaxSize],*p; int top=-1;   p=b;   while (top>-1 || p!=NULL)   {  while (p!=NULL)  { top++; St[top]=p;   p=p->lchild; }           if (top>-1) {  p=St[top];top--;               printf("%c ",p->data);     p=p->rchild;               }   }} //⑧、编写后序遍历非递归算法;void PostOrder1(BTNode *b){  BTNode *St[MaxSize];BTNode *p;   int flag,top=-1;     do   {  while (b!=NULL)        {  top++; St[top]=b;    b=b->lchild; }               p=NULL;  flag=1;   while (top!=-1 && flag==1)   {  b=St[top];       if (b->rchild==p) {  printf("%c ",b->data);    top--;p=b; } else       {    b=b->rchild;            flag=0;       }        }  } while (top!=-1);} //⑨、编写主函数。void main(){BTNode *t = NULL;char str[50] = "Q(W(E(R(,T)),Y(,U)I)";CreateBTNode(t,str);printf("二叉树:");DispBTNode(t);printf("\n");printf("后序遍历递归:");PostOrder(t);printf("\n");printf("中序遍历递归:");InOrder(t);printf("\n");printf("先序遍历递归:");PreOrder(t);printf("\n");printf("先序遍历非递归:");PreOrder1(t);printf("\n");printf("中序遍历非递归:");InOrder1(t);printf("\n");printf("后序遍历非递归:");PostOrder1(t);printf("\n");}


0 0
原创粉丝点击