二叉树的基本操作

[问题描述]
建立一棵二叉树,试编程实现二叉树的如下基本操作:

  1. 按先序序列构造一棵二叉链表表示的二叉树T;
  2. 对这棵二叉树进行遍历:先序、中序、后序以及层次遍历,分别输出结点的遍历序列;
  3. 求二叉树的深度/结点数目/叶结点数目;(选做)
    [基本要求]
    从键盘接受输入(先序),以二叉链表作为存储结构,建立二叉树(以先序来建立),
    [测试数据]
    如输入:ABCффDEфGффFффф(其中ф表示空格字符)
    ABC##DE#G##F###
      则输出结果为
    先序:ABCDEGF
    中序:CBEGDFA
    后序:CGEFDBA
    层序:ABCDEFG

代码如下

#include<iostream>
#include<stdio.h>
using namespace std;
typedef struct tree
{
char data;
tree *leftchild;
tree *rightchild;
}*BiTree,BiTNode;


//创建二叉树,以#号代表空 

void CreatBiTree(BiTree &T)
{
char ch;
cin>>ch;
if(ch=='#')
	T=NULL;
else
{
	T=new BiTNode;
	T->data=ch;
	CreatBiTree(T->leftchild);
	CreatBiTree(T->rightchild);
}
}

//先序 

void DLR(BiTree &T)
	{
    if(T)
    {
        cout<<T->data;
        DLR(T->leftchild);
        DLR(T->rightchild);
    }
	}

//中序 

void LDR(BiTree &T)
{
if(T)
{
    LDR(T->leftchild);
	cout<<T->data;
    LDR(T->rightchild);
}
}

//后序 
void LRD(BiTree &T)
{
if(T)
{
	LRD(T->leftchild);
    LRD(T->rightchild);
	cout<<T->data;
}
}

//层序
void floor(BiTree &T)  
{
BiTree t[100];
int i=0,j=0;
t[i++]=T;
while (i>j)
{
    if (t[j])
    {
        cout<<t[j]->data;
        t[i++]=t[j]->leftchild;
        t[i++]=t[j]->rightchild;
    }
    j++;
}
}

//深度 
int  Depth(BiTree &T)
{
if(!T)
return 0;
else
{
	int m,n;
	m=Depth(T->leftchild);//左子树深度m 
	n=Depth(T->rightchild);//右子树深度n 
	if(m>n)
	return m+1;
	else
	return n+1;
}
}

//结点
int NodeCount(BiTree &T)
{
if(!T)
    return 0;
    int n=NodeCount(T->leftchild)+NodeCount(T->rightchild)+1;
    //左子树+右子树+根节点 
return n;
}
//叶节点数 

void yecount(BiTree &T)
{ 
if(T)
{
    if(T->leftchild==NULL&&T->rightchild==NULL)
    {
        i++;
    }
    else
    {
        yecount(T->leftchild);
        yecount(T->rightchild);
    }
}
}
//主函数
int main()
{
BiTree T;
cout<<"请输入一颗二叉树"<<endl;
CreatBiTree(T);
cout<<"\n先序遍历是"<<endl;
DLR(T);
cout<<"\n中序遍历是"<<endl; 
LDR(T);
cout<<"\n后序遍历是"<<endl; 
LRD(T);
cout<<"\n层序遍历是"<<endl;
floor(T); 
cout<<"\n二叉树的深度是"<<endl;
cout<<Depth(T);
cout<<"\n二叉树的结点数是"<<endl; 
cout<<NodeCount(T);
return 0;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值