#include<stdio.h>
#include<stdlib.h>
int depth = 0;
typedef struct Node {
         char data;
         struct Node *Lchild;
         struct Node *Rchild;
}BiTNode,*BiTree;
BiTree *InitBiTree(BiTree *BiTree)
{
         *BiTree = (BiTNode *)malloc(sizeof(BiTNode));
         (*BiTree)->Lchild = NULL;
         (*BiTree)->Rchild = NULL;
         return BiTree;
}
BiTNode *CreateBiTree() {
         BiTNode *bt;
         char c;
         scanf(\"%c\",&c);
         if (c == \'$\')
                  bt = NULL;
        else
        {
              bt = (BiTree)malloc(sizeof(BiTNode));
              bt->data = c;
               bt->Lchild = CreateBiTree();
               bt->Rchild = CreateBiTree();
         }
         return bt;
}
void PreOrder(BiTree root) {
         if(root != NULL) {
                  printf(\"%4c\",root->data);
                  PreOrder(root->Lchild);
                  PreOrder(root->Rchild);
         }
}
void InOrder(BiTree root) {
         if(root != NULL) {
	InOrder(root->Lchild);
	printf(\"%4c\",root->data);
	InOrder(root->Rchild);
         }
}
void PostOrder(BiTree root) {
         if(root != NULL) {
                  PostOrder(root->Lchild);
                  PostOrder(root->Rchild);
                  printf(\"%4c\",root->data);
         }
}
int PostTreeDepth(BiTNode *bt) {
         if(bt) {
                  return 
                  PostTreeDepth(bt->Lchild)>PostTreeDepth(bt->Rchild) ?
                  PostTreeDepth(bt->Lchild) + 1 : PostTreeDepth(bt->Rchild) + 1;
         }
         if(bt == NULL)
                  return 0;
}
void PrintTree(BiTree bt, int n ) {
         if(bt == NULL)
                  return;
         PrintTree(bt->Rchild,n  + 1);
         for(int i = 0; i < n ; i++) {
                  printf(\"\\t\");
         }
         printf(\"%c\\n\",bt->data);
         PrintTree(bt->Lchild,n  + 1);
}
int Leafnum(BiTNode* root)
{
         if(!root)
                  return 0;
         else if ((root->Lchild == NULL) && (root->Rchild == NULL))
                  return 1;
         else
                  return (Leafnum(root->Lchild) + Leafnum(root->Rchild));
}
int main()
{
	   BiTNode *TwoTree=NULL;
           char c;
           int high,h=1,num,n =1;
           printf(\"请输入各个结点的数据.\\n\");
           TwoTree  = CreateBiTree();
           printf(\"二叉树建立成功\\n\");
           printf(\"打印该二叉树\\n\");
           PrintTree(TwoTree,n );
           printf(\"先序遍历结果为:\");
           PreOrder(TwoTree);
           printf(\"\\n\");
           printf(\"中序遍历结果为:\");
           InOrder(TwoTree);
           printf(\"\\n\");
           printf(\"后序遍历结果为:\");
           PostOrder(TwoTree);
           printf(\"\\n\");
           high=PostTreeDepth(TwoTree);
           printf(\"二叉树高度为:%d\",high);
           printf(\"\\n\");
           num=  Leafnum(TwoTree);
           printf(\"叶子结点数目为:%d\\n\",num);    
           return 0;
  }
收藏 打印