您的位置:首页 > 编程语言 > C语言/C++

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

2013-12-14 01:25 381 查看
#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 二叉树