二叉树遍历及简单应用

来源:互联网 发布:街霸5网络功能已禁用 编辑:程序博客网 时间:2024/06/06 13:59
#include "stdafx.h"
#include <iostream>
using namespace std;
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;//结点数据变量
struct BiTNode *Lchild;//左孩子指针
struct BiTNode *Rchild;//右孩子指针 
} BiTNode ,*BiTree;


//先序遍历
void Preorder (BiTree T)
{ //先序遍历以T为根指针的二叉树
if (T)
{ //二叉树为空,不做任何操作
printf("%c  ",T->data);                         // 通过函数指针访问根结点 
Preorder(T->Lchild); //先序遍历左子树
Preorder(T->Rchild); //先序遍历右子树
}
}


//中序遍历
void Inorder (BiTree T)
{ //中序遍历以T为根指针的二叉树
if (T)
{ //二叉树为空树,不做任何操作
Inorder(T->Lchild);//中序遍历左子树
printf("%c  ",T->data);    //通过函数指针访问根结点
Inorder(T->Rchild); //中序遍历右子树
}
}


//后序遍历
void Postorder (BiTree T)
{ //后序遍历以T为根指针的二叉树
if (T)
{ //二叉树为空树,不做任何操作
Postorder(T->Lchild);//后序遍历左子树
Postorder(T->Rchild); //后序遍历右子树
printf("%c  ",T->data);  //通过函数指针访问根结点
}
}
void BiTreeDepth(BiTree T, int level, int &depth)
{ //T指向二叉树的根,level 为 T 所指结点所在层次, 其初值为1,depth当前求得的最大层次,初值为0
if (T)
{
if (level>depth)
depth=level; 
BiTreeDepth(T->Lchild, level+1, depth);
BiTreeDepth(T->Rchild, level+1, depth);
}
}
void CountLeaf (BiTree T, int& count)
{ //树中叶子结点的数目
if(T)
{
if((!T->Lchild)&&(!T->Rchild))
count++; //对叶子结点计数 
CountLeaf( T->Lchild, count);
CountLeaf( T->Rchild, count); 

}




//
///构造二叉树
void createbt(BiTree& T)
{
char ch;
scanf_s("%c",&ch);
if(ch=='#')
{T=NULL;}
else{
T=(BiTree)malloc(sizeof(BiTNode));
T->data=ch;
createbt(T->Lchild);
createbt(T->Rchild);
}
}


//        A
//       /
// B
// / \
// C  D
//        / \
//  E  F
//   \
//    G
//#代表子树结点为空值
int _tmain(int argc, _TCHAR* argv[])
{
BiTree T;
int depth,counter=0;
printf("create a tree such as ABC##DE#G##F### \n");
createbt(T);


printf("先序遍历\n");
Preorder (T);
cout<<endl;
printf("中序遍历\n");
Inorder (T);
cout<<endl;
printf("后序遍历\n");
Postorder(T);
cout<<endl;
//------------------简单应用---------------------\\


    printf("二叉树的深度\n");
BiTreeDepth(T, 1, depth);
printf("%d\n",depth);
cout<<endl;


printf("统计二叉树中叶子结点的个数\n");
CountLeaf(T, counter);
printf("%d\n",counter);


system("pause");
return 0;
}