二叉树算法集

作者:袖梨 2022-07-02

#include
#include
#define MAX  50
#define MAS  20
#define CHAR 1
#if CHAR
   typedef char TElemType;
   TElemType Nil=' ';
   #define form "%c"
#else
   typedef int TElemType;
   TElemType Nil=0;
   #define form "%d"
#endif
typedef struct node
{TElemType data;
 struct node *left;
 struct node *right;
 struct node *parent;
}BiTNode,*BiTree;
BiTNode *InitBiTree(BiTNode *bt)
{
 bt=NULL;
 return bt;
}
BiTNode *CreateBiTree(BiTNode *bt)
{TElemType ch;
 scanf(form,&ch);
 if(ch==Nil) bt=NULL;
  else
  {bt=(BiTNode *)malloc(sizeof(BiTNode));
   if(!bt) exit(0);
   bt->data=ch; bt->parent=NULL;
   bt->left=CreateBiTree(bt->left);
   if(bt->left) bt->left->parent=bt;
   bt->right=CreateBiTree(bt->right);
   if(bt->right) bt->right->parent=bt;
  }
  return bt;
}
void PrintTree(BiTNode *bt,int i)
{ if(bt!=NULL)
  {PrintTree(bt->right,i+5);
   #if CHAR
    if(bt->data!=Nil)
    printf("%*cn",i,bt->data);
   #else
    if(bt->data!=Nil)
    printf("%*dn",i,bt->data);
   #endif
   PrintTree(bt->left,i+5);
   i=i-5;
  }
}
void Prorder1(BiTNode *bt,void(*visit)(TElemType))/*先序遍历*/
{if(bt!=NULL)
 {visit(bt->data);
  Prorder1(bt->left,visit);
  Prorder1(bt->right,visit);
 }
}
void Prorder2(BiTNode *bt,void(*visit)(TElemType))/*中序遍历*/
{BiTNode *p,*stack[MAS];
 int top;
 top=0;  p=bt;
 while(top!=0||p!=NULL)
 {while(p!=NULL)
  {stack[top]=p; top++;
   p=p->left;
  }
  if(top!=0)
  {p=stack[top-1];
   top--;
   visit(p->data);
   p=p->right;
  }
 }
}
void Prorder3(BiTNode *bt,void(*visit)(TElemType))/*后序遍历*/
{BiTNode *p,

相关文章

精彩推荐