二叉树基于遍历的进一步操作c++实现

#include <iostream>
#include <string>


using namespace std;


//二叉树的数据结构
typedef char BiTType;


typedef struct BiTNode
{
BiTType data;
BiTNode *lChild,*rChild;
}BiTNode,*BiTree;


//二叉树的类


class BinaryTree
{
private:
//创建二叉树字符串类
string create;
//指向字符的下标
int index;
//二叉树的根
BiTree root;
//二叉树de叶子的树木
int leaf;
//当前访问的节点的层数
int now;
void Create(BiTree & T);
int Level(BiTree & T);
void Leaf(BiTree & T);
void print(BiTree & T);
public:
BinaryTree();
BinaryTree(char *S);
//计算二叉树的层数
int CountLevel();
//计算二叉树的叶子的树木
int CountLeaf();
//横向打印二叉树
void Print();
};


BinaryTree::BinaryTree()
{
this->root = NULL;
}


BinaryTree::BinaryTree(char *S)
{
this->create = S;
this->index = 0;
this->Create(this->root);
}


void BinaryTree::Create(BiTree & T)
{
BiTType temp;
if((temp = this->create[this->index++]) == '#')
{
T = NULL;
}
else
{
T = new BiTNode;
T->data = temp;
Create(T->lChild);
Create(T->rChild);
}
}


int BinaryTree::CountLevel()
{
return this->Level(this->root);
}


//算法思想就是利用后序遍历,先遍历完成左右子树以后判断
//最大值再加上一,就是二叉树的层数
int BinaryTree::Level(BiTree & T)
{
if(!T)
{
return 0;
}
else
{
int l = Level(T->lChild);
int r = Level(T->rChild);
return l>r?l+1:r+1;
}
}


int BinaryTree::CountLeaf()
{
this->leaf = 0;
this->Leaf(this->root);
return this->leaf;
}


//先序遍历(其实任何一种遍历都可以)
void BinaryTree::Leaf(BiTree & T)
{
if(T)
{
if(!T->lChild && !T->rChild)
this->leaf++;
if(T->lChild)
Leaf(T->lChild);
if(T->rChild)
Leaf(T->rChild);
}
}


void BinaryTree::Print()
{
this->now = 0;
this->print(this->root);
}


//运用中序遍历的思想,先打印左边的子树
//后打印右边的子树
//now代表子树的度,可以打印几个空格
void BinaryTree::print(BiTree & T)
{
this->now++;
if(T->lChild)
this->print(T->lChild);
for(int i=0;i<this->now;i++)
{
cout<<"          ";
}
cout<<T->data<<endl;
if(T->rChild)
this->print(T->rChild);
this->now--;
}


int main()
{
BinaryTree BT("abc##de###f#g#h##");
cout<<"树的叶子数目"<<BT.CountLeaf()<<endl;
cout<<"树的度"<<BT.CountLevel()<<endl;
cout<<"打印树";
cout<<endl;
BT.Print();
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值