⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 btree.cpp

📁 用C++实现的一个二叉树模板类
💻 CPP
字号:
#include <iostream>
#include <iomanip>
using namespace std;

//*************************************************************************************
//二叉树结点类的定义
template<class T>
struct BTNode
{
	T data;
	BTNode <T> * left,*right;
	BTNode(T nodeValue = T(),BTNode<T>* leftNode = NULL,BTNode<T>* rightNode = NULL )
		:data(nodeValue),left(leftNode),right(rightNode){}       //可选择参数的默认构造函数
};

//*******************************************************************
//基本的二叉树类
template <class T> class BTree
{

public:
	BTree(BTNode <T> *root );
	~BTree(){MakeEmpty();}
	void MakeEmpty(){destroy(root); root=NULL;}

	void createBTree(BTNode<T> *&root);
	void preOrder(BTNode<T> *&root);
protected:
	BTNode<T> *root;
private:
	void destroy(BTNode<T> *p)
	{
		if(p)
		{
			destroy(p->left);
			destroy(p-right);
			delete p;
		}
	}
};

template <class T> BTree<T>::BTree(BTNode<T> *root =NULL)
{
	root=root;
}
template <class T> void BTree<T>::createBTree(BTNode<T> *&root)
{
	BTNode<T> *p = root;
	BTNode<T> *k=NULL;
	T nodeValue;
	cin>>nodeValue;
	if(nodeValue==-1)
	{
		root=NULL;
	}
	else
	{
		root=new BTNode<T>();
		root->data=nodeValue;
		createBTree(root->left);
		createBTree(root->right);
	}
}
template <class T>void BTree<T>::preOrder(BTNode<T> *&root)
{
	if(root)
	{
		cout<<setw(4)<<root->data;
		preOrder(root->left);
		preOrder(root->right);
	}
}
// void main()
// {
// 	BTree<int> *t=NULL;
// 	BTNode<int> * root=NULL;
// 	t->createBTree(root);
// 	t->preOrder(root);
// 
// }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -