BinaryTree.h
#pragma once
template <class T>
struct BinaryTreeNode
{
BinaryTreeNode<T>* _right;
BinaryTreeNode<T>* _left;
T _data;
BinaryTreeNode(const T& d)
:_right(NULL)
,_left(NULL)
,_data(d)
{}
};
template <class T>
class BinaryTree
{
typedef BinaryTreeNode<T> Node;
public:
BinaryTree()
:_root(NULL)
{}
BinaryTree(const T* a, size_t size, const T& invalid)
{
size_t index = 0;
_root = _CreatTree(a, size, index, invalid);
}
BinaryTree(const BinaryTree<T>& t)
{
_root = _CopyTree(t._root);
}
~BinaryTree()
{
_Destory(_root);
_root = NULL;
}
size_t Size() //求二叉树结点数目
{
return _Size(_root);
}
size_t Depth() //求二叉树深度
{
return _Depth(_root);
}
void PrevOrder() //前序遍历
{
_PrevOrder(_root);
cout<<endl;
}
protected:
Node* _CreatTree(const T* a, size_t size, size_t& index, const T& invalid)
{
Node* root = NULL;
if(index<size && a[index]!=invalid)
{
root = new Node(a[index]);
root->_left = _CreatTree(a, size, ++index, invalid);
root->_right = _CreatTree(a, size, ++index, invalid);
}
return root;
}
Node* _CopyTree(const Node* root)
{
if(root == NULL)
{
return NULL;
}
Node* newRoot = new Node(root->_data);
newRoot->_left = _CopyTree(root->_left);
newRoot->_right = _CopyTree(root->_right);
return newRoot;
}
void _Destory(Node* root)
{
if(root == NULL)
{
return;
}
_Destory(root->_left);
_Destory(root->_right);
delete root;
}
size_t _Size(Node* root)
{
if(root == NULL)
{
return 0;
}
return _Size(root->_left)+_Size(root->_right)+1;
}
size_t _Depth(Node* root)
{
if(root == NULL)
{
return 0;
}
size_t leftDepth = _Depth(root->_left);
size_t rightDepth = _Depth(root->_right);
return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;
}
void _PrevOrder(Node* root)
{
if(root == NULL)
{
return;
}
cout<<root->_data<<",";
_PrevOrder(root->_left);
_PrevOrder(root->_right);
}
private:
Node* _root;
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。