main.cpp
#include <iostream>
#include"bitnode.h"
using namespace std;
int main()
{
bitree T=NULL;
int m;
printf("*********采用递归函数构造一棵二叉树******\n");
printf("请读入构造二叉树的字符序列:");
if(T=creatbitree(T))
{
printf("二叉树建立成功! 并以层次遍历输出构造的二叉树\n");
cout<<T->data<<endl;
m=levelorder(T);
printf("\n该二叉树的叶子结点个数是:%d\n",m);
printf("\n");
cout<<"先序遍历"<<endl;
preordertraverse(T);
cout<<endl;
cout<<"中序遍历"<<endl;
inordertraverse(T);
cout<<endl;
cout<<"后序遍历"<<endl;
postordertraverse(T);
cout<<endl;
cout<<"\ndepth is ---------- "<<depth(T)<<endl;
}
else
printf("很遗憾,不能成功建立二叉树!!!\n");
return 0;
}
bitree.h
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAX 20
#define OK 1
#define ERROR 0
#define NULL 0
#define OVERFLOW 0
using namespace std;
typedef char telemtype;
typedef int status;
typedef struct bitnode
{
telemtype data;
struct bitnode *lchild ,*rchild;
}bitnode,*bitree;
//先序遍历构造二叉树
bitree creatbitree(bitree T)
{
char ch;
scanf("%c",&ch);
if(ch=='#') T=NULL;
else
{
T=new bitnode;
// cout<<"createbitree else"<<endl;
T->data=ch;
T->lchild=creatbitree(T->lchild);
T->rchild=creatbitree(T->rchild);
}
return T;
}
int levelorder(bitree T)
{
bitree queue[MAX],b;
//用一维数组表示队列,front和rear 分别表示队首和队尾指针
int front,rear;
int m=0;
front=rear=0;
if(T)
{
queue[rear++]=T;
while(front!=rear)
{
b=queue[front++];
// printf("%c-",b->data );
cout<<b->data<<'-';
if(b->lchild !=NULL)
queue[rear++]=b->lchild ;//左子树非空,则入队列
if(b->rchild !=NULL)
queue[rear++]=b->rchild ;
if(b->lchild==NULL && b->rchild==NULL){
m++;
}
}
}
return m;
}
void preordertraverse(bitree T) //先序遍历
{
// cout<<"先序遍历"<<endl;
cout<<T->data;
if(T->lchild!=NULL){
preordertraverse(T->lchild);
}
if(T->rchild!=NULL){
preordertraverse(T->rchild);
}
}
void inordertraverse(bitree T) //中序遍历
{
// cout<<"中序遍历"<<endl;
if(T->lchild!=NULL){
inordertraverse(T->lchild);
}
cout<<T->data;
if(T->rchild!=NULL){
inordertraverse(T->rchild);
}
}
void postordertraverse(bitree T) //后序遍历
{
// cout<<"后序遍历"<<endl;
if(T->lchild!=NULL){
postordertraverse(T->lchild);
}
if(T->rchild!=NULL){
postordertraverse(T->rchild);
}
cout<<T->data;
}
int depth(bitree T)
{
if(T==NULL) return 0;
if(T->lchild==NULL && T->rchild==NULL) return 1;
return depth(T->lchild)>depth(T->rchild)?depth(T->lchild)+1:depth(T->rchild)+1;
}