二叉树:
二叉树作为数据结构的树中的一个分支,非常的重要。
二叉树的概念这里就不在赘述。
二叉树是采用递归定义的,代码实现起来简洁(其实也并不简单),并且它在具体的计算科学中有很重要的应用,是一种非常重要的数据结构。
二叉树的创建:
1、二叉树是有节点构成的,每个节点又都可以看做一个三元组。包括:数据域、左指针域、右指针域。
2、二叉树可以在类中去创建,包括构造函数、拷贝构造函数、析构函数还有真正的创建函数和节点释放函数。
3、二叉树是由递归定义的,创建二叉树也少不了递归的应用。
二叉树这里直接贴上代码!
#include<iostream>
using namespace std;
#pragma once
template<class T>
struct BinaryTreeNode//三元组创建节点
{
BinaryTreeNode(const T& data)
: _data(data)
, _pLeft(NULL)
, _pRight(NULL)
{}
T _data;
BinaryTreeNode<T>* _pLeft;
BinaryTreeNode<T>* _pRight;
};
template<class T>
class BinaryTree
{
public:
BinaryTree()//构造函数 ——空树
:_pRoot(NULL)
{}
BinaryTree(const T arr[], size_t size)//构造函数---创建树
{
size_t index = 0;
_CreatTree(_pRoot, arr, size, index);
}
void _CreatTree( BinaryTreeNode<T>*& pRoot, const T arr[], size_t size, size_t& index)
{
if (index<size && arr[index] != '#')
{
pRoot = new BinaryTreeNode<T>(arr[index]);
_CreatTree(pRoot->_pLeft, arr, size, ++index);
_CreatTree(pRoot->_pRight, arr, size, ++index);
}
}
BinaryTree(const BinaryTree<T>& t)//拷贝构造函数
{
_pRoot = _CopyTree(t.pRoot);
}
BinaryTreeNode<T>* _CopyTree(BinaryTreeNode<T>*& pRoot)
{
BinaryTreeNode<T>* newpRoot = NULL;
if (pRoot)
{
newpRoot = new BinaryTreeNode<T>(pRoot->data);
newpRoot->_pLeft = _CopyTree(pRoot->_pLeft);
newpRoot->_pRight = _CopyTree(pRoot->_pRight);
}
return newpRoot;
}
BinaryTree<T>& operator=(const BinaryTree<T>& t)//赋值运算符重载
{
if (this != &t)
{
_DestroyTree(_pRoot);
_pRoot = _CopyTree(t.pRoot);
}
return *this;
}
~BinaryTree()//析构函数
{
_DestroyTree(_pRoot);
}
void _DestroyTree(BinaryTreeNode<T>*& pRoot)//释放节点的函数
{
if (pRoot)
{
_DestroyTree(pRoot->_pLeft);
_DestroyTree(pRoot->_pRight);
delete pRoot;
pRoot = NULL;
}
}
private:
BinaryTreeNode<T>* _pRoot;
};
int main()
{
char arr[] = { '0', '1', '3', '#', '#', '4', '#', '#', '2', '5' };
BinaryTree<char> t (arr, sizeof(arr) / sizeof(arr[0]));
return 0;
}