二叉树先序、中序、后序遍历

来源:互联网 发布:line是什么软件 编辑:程序博客网 时间:2024/06/07 00:34
 #include<iostream.h>
#include<stdio.h>

int count=0;
typedef struct BiTNode // 结点结构
{
    char   data;
    struct BiTNode  *lchild, *rchild;
                                     // 左右孩子指针
} BiTNode, *BiTree;
//创建结点
char CreateBiTree(BiTree &T)
{   char ch;
    scanf("%c",&ch);
    if (ch=='#') T = NULL;
    else
 {
        if (!(T = new BiTNode))
        return 1;
        T->data = ch;              // 生成根结点
        CreateBiTree(T->lchild);   // 构造左子树
        CreateBiTree(T->rchild);   // 构造右子树
    }
    return 0;
 } // CreateBiTree
void PrintElement(char e)
{
 printf("%c",e);

}

// 先序遍历二叉树
 
char  PreOrder (BiTree T,void visit(char e))
                 
{
   if (T)
   {
      visit(T->data);            // 访问结点
      PreOrder(T->lchild, visit); // 遍历左子树
      PreOrder(T->rchild, visit);// 遍历右子树
   }
   return 0;
}
// 中序遍历二叉树
 
char  InOrder (BiTree T,void visit(char e) )
                 
{
   if (T)
   {
      InOrder(T->lchild, visit); // 遍历左子树
      visit(T->data);            // 访问根结点
      InOrder(T->rchild, visit);// 遍历右子树
   }
 return 0;
}
// 后序遍历二叉树

char PostOrder (BiTree T,void visit(char e))
                 

   if (T)
   {
     PostOrder(T->lchild, visit); // 遍历左子树
      PostOrder(T->rchild, visit);// 遍历右子树
      visit(T->data);            // 访问根结点
   }
 return 0;
}

 // 对叶子结点计数

int CountLeaf (BiTree T)
{
 int n=0;
 int &count=n;

   if (T)
   {
      if ((!T->lchild)&& (!T->rchild))
         count++;   
      CountLeaf( T->lchild); 
      CountLeaf( T->rchild);
   } // if

return count;
} // CountLeaf

// 返回二叉树的深度

int Depth (BiTree T )
{
 int depthval;
 int depthLeft;
 int  depthRight;
   if ( !T )  
    depthval = 0;
   else
   {
     depthLeft = Depth( T->lchild );
     depthRight= Depth( T->rchild );
     depthval = 1 + (depthLeft > depthRight ?depthLeft : depthRight);
                              
   }
   return depthval;
}

int main()
{
 //int m;
 BiTree type;
 cout<<"创建结点"<<endl;

 CreateBiTree(type);

cout<<endl;
 cout<<"先序遍历左节点"<<endl;
 PreOrder (type,PrintElement);

cout<<endl;
 
 cout<<"先先序遍历左节点"<<endl;
 InOrder(type, PrintElement);

cout<<endl;

cout<<"先先序遍历左节点"<<endl;
 PostOrder(type, PrintElement);

cout<<endl;

cout<<"计算叶子总数"<<endl;
 cout<<CountLeaf (type)<<endl;
cout<<"计算深度"<<endl;
cout<< Depth (type)<<endl;
 return 0;
}

原创粉丝点击