二叉树遍历及简单应用

#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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值