数据结构:二叉树的实现(C++)

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);
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值