二叉树的实现

二叉树的实现

树的节点通过定义BinTreeNode结构体来实现,二叉树则由BinaryTree类实现。
BinTree.h 头文件

//BinTree.h
#include<iostream>
#include<queue>
using namespace std;

struct BinNode
{
	char data;
	BinNode *leftChild, *rightChild;
};

class BinTree
{
	private:
		BinNode *root;
		char stopValue, nullValue;
	public:
		BinTree();
		BinNode* getRoot();
		void preOrder(BinNode *node);
		void inOrder(BinNode *node);
		void postOrder(BinNode *node);
		void levelOrder(BinNode *node);
		int NodeNum(BinNode *node);
		int TreeDepth(BinNode *node);
		int LeafNum(BinNode *node);
		BinNode* Create();
};

BinTree::BinTree()
{
	root = new BinNode;
	nullValue = '#';
	root = Create();
}

BinNode* BinTree::Create()
{
	char ch;
	cin >> ch;
	BinNode *pnode;
	if(ch == '#')
		pnode = NULL;
	else
	{
		pnode = new BinNode;
		
		pnode->leftChild = Create();
		pnode->data = ch;
		pnode->rightChild = Create();
	}
	return pnode;
}

BinNode* BinTree::getRoot()
{
	return root;
}

void BinTree::preOrder(BinNode *node)
{
	if(!node)
		return ;
	cout << node->data << ' ';
	preOrder(node->leftChild);
	preOrder(node->rightChild);
}

void BinTree::inOrder(BinNode *node)
{
	if(!node)
		return ;
	inOrder(node->leftChild) ;
	cout << node->data << ' ';
	inOrder(node->rightChild);
}

void BinTree::postOrder(BinNode *node)
{
	if(!node)
		return ;
	postOrder(node->leftChild);
	postOrder(node->rightChild);
	cout << node->data << ' ';
}

void BinTree::levelOrder(BinNode *node)
{
	queue<BinNode *> q;
	BinNode *s = node;
	if(!s)
		return ;
	q.push(s);
	while(!q.empty())
	{
		s = q.front();
		q.pop();
		cout << s->data << ' ';
		if(s->leftChild)
			q.push(s->leftChild);
		if(s->rightChild)
			q.push(s->rightChild);
	}
}

int BinTree::LeafNum(BinNode *node)
{
	if(!node)
		return 0;
	if(!node->leftChild && !node->rightChild)
		return 1;
	return LeafNum(node->leftChild) + LeafNum(node->rightChild);
}

int BinTree::NodeNum(BinNode *node)
{
	if(!node)
		return 0;
	return 1 + NodeNum(node->leftChild) + NodeNum(node->rightChild);
}

int BinTree::TreeDepth(BinNode *node)
{
	if(!node)
		return 0;
	int ldepth=TreeDepth(node->leftChild);
	int rdepth=TreeDepth(node->rightChild);
	return max(ldepth, rdepth)+1;
}

测试程序main.cpp

//main.cpp
#include<iostream>
#include"BinTree.h"
using namespace std;

int main()
{
	BinTree a;
	cout<<"preorder:";
	a.preOrder(a.getRoot());
	cout<<endl;
	cout<<"inorder:";
	a.inOrder(a.getRoot());
	cout<<endl;
	cout<<"postorder:";
	a.postOrder(a.getRoot());
	cout<<endl;
	cout<<"leafnum:"<<a.LeafNum(a.getRoot());
	cout<<endl;
	cout<<"nodenum:"<<a.NodeNum(a.getRoot());
	cout<<endl;
	cout<<"treedepth:"<<a.TreeDepth(a.getRoot());
	cout<<endl;
	return 0;
}

/*
										A
						B									C
		D					E						F					G		 
#				#	#				#		#				#	#				#
*/
//ABD##E##CF##G##(先序建树)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值