Mi_Tree测试数据:
Mi_Tree实现:
#include "stdafx.h"
#include <iostream>
using namespace std;
//二叉树:递归实现的二叉树。万能的递归。
class Mi_Tree {
public:
class Element {
public:
Element() {
pLeft = 0;
data = 0;
pRight = 0;
}
Element* pLeft;
Element* pRight;
char data;
};
public:
Mi_Tree() {
size = 0;
}
//前序输出二叉树
void PrintNLR(Element*);
//中序输出二叉树
void PrintLNR(Element*);
//后序输出二叉树
void PrintLRN(Element*);
//输出叶结点数量
int GetLeafsCount(Element*);
//输出树的高度
int GetTreeHeight(Element *);
//前序创建二叉树
Element* CreateTreeWithNLR();
//树的Size
inline int GetTreeSize() {
return size;
}
int size;
Element* root;
};
Mi_Tree::Element* Mi_Tree::CreateTreeWithNLR() {
char c;
cin >> c;
Element *e = new Element();
if ('#' == c) {
e = 0;
}
else {
e->data = c;
e->pLeft = CreateTreeWithNLR();
e->pRight = CreateTreeWithNLR();
size++;
}
root = e;
return e;
}
void Mi_Tree::PrintNLR(Element* _e) {
if (_e != 0) {
cout << _e->data << ' ';
PrintNLR(_e->pLeft);
PrintNLR(_e->pRight);
}
}
void Mi_Tree::PrintLNR(Element* _e)
{
if (_e != 0) {
PrintLNR(_e->pLeft);
cout << _e->data << ' ';
PrintLNR(_e->pRight);
}
}
void Mi_Tree::PrintLRN(Element *_e)
{
if (_e != 0) {
PrintLRN(_e->pLeft);
PrintLRN(_e->pRight);
cout << _e->data << ' ';
}
}
int Mi_Tree::GetTreeHeight(Element *_e)
{
if (0 == _e) {
return 0;
}
int l = GetTreeHeight(_e->pLeft);
int r = GetTreeHeight(_e->pRight);
return l>r ? (l + 1) : (r + 1);
}
int Mi_Tree::GetLeafsCount(Element *_e) {
if (0 == _e) {
return 0;
}
if (0 == _e->pLeft && 0 == _e->pRight) {
return 1;
}
int i = GetLeafsCount(_e->pLeft);
int j = GetLeafsCount(_e->pRight);
return i + j;
}
Mi_List测试:
void TestTree() {
cout << "Mi_Tree测试:请输入扩展二叉树,#为结束结点'。" << endl;
Mi_Tree tree;
tree.CreateTreeWithNLR();
cout << "前序输出二叉树:" << endl;
tree.PrintNLR(tree.root);
cout << endl;
cout << "中序输出二叉树:" << endl;
tree.PrintLNR(tree.root);
cout << endl;
cout << "后序输出二叉树:" << endl;
tree.PrintLRN(tree.root);
cout << endl;
cout << "Root节点值:" << tree.root->data << endl;
cout << "树的Size:" << tree.size << endl;
cout <<"树的高度:"<< tree.GetTreeHeight(tree.root) << endl;
cout <<"叶结点数量(非#节点):"<<tree.GetLeafsCount(tree.root);
}