二叉树的前序中序后序遍历算法,并计算二叉树的深度和结点个数

#include
#include
using namespace std;


typedef char ElemType;
typedef struct BiTNode//二叉树结点定义
{
    ElemType data;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;


//按照前序遍历序列建立一颗二叉树
void CreateBiTree(BiTree *T)
{
    ElemType ch;
    cin>>ch;
    if(ch=='#')
    *T=NULL;
    else
    {
        *T=(BiTree )malloc(sizeof(BiTNode));
        (*T)->data=ch;
        CreateBiTree(&(*T)->lchild);
        CreateBiTree(&(*T)->rchild);
    }
}
void operation(ElemType ch)
{
    cout<}
 //前序遍历的递归算法
 void preorder(BiTree T)
 {
     if(T)
     {
         operation(T->data);
         preorder(T->lchild);
         preorder(T->rchild);
     }
 }
 //中序遍历的递归算法
 void inorder(BiTree T)
 {
     if(T)
     {
         inorder(T->lchild);
         operation(T->data);
         inorder(T->rchild);
     }
 }
 //后序遍历的递归算法
 void postorder(BiTree T)
 {
     if(T)
     {
         postorder(T->lchild);
         postorder(T->rchild);
         operation(T->data);
     }
 }
 int BiTNodeDepth(BiTNode *T) //求二叉树的深度
 {
     int lchilddep,rchilddep;
     if(T==NULL)
     return 0;
     else
     {
         lchilddep=BiTNodeDepth(T->lchild);
         rchilddep=BiTNodeDepth(T->rchild);
         int ret=max(lchilddep,rchilddep)+1;
         return ret;
     }
 }
 int GetNodeCount(BiTNode *T)//求结点个数
 {
     if(T==NULL)
     return 0;
     int LeftNum=GetNodeCount(T->lchild);
     int RightNum=GetNodeCount(T->rchild);
     int ret=LeftNum+RightNum+1;
     return ret;
 }




 int main()
 {
     BiTree T=NULL;
     cout<<"请按二叉树的前序遍历输入各结点:";
     CreateBiTree(&T);
     cout<<"先序遍历二叉树序列为:"<     preorder(T);
     cout<     cout<<"中序遍历二叉树序列为;"<     inorder(T);
     cout<     cout<<"后序遍历二叉树序列为:"<     postorder(T);
     cout<     cout<<"二叉树的深度为: "<     cout<     cout<<"二叉树的结点个数为:"<     cout<     return 0;
 }

你可能感兴趣的:(二叉树的前序中序后序遍历算法,并计算二叉树的深度和结点个数)