您好,登錄后才能下訂單哦!
對于二叉樹的實現(xiàn)主要運用遞歸進行實現(xiàn),代碼如下:
#include <assert.h>
template<class T>
struct BinaryTreeNode
{
T _data;
BinaryTreeNode<T> *_left;
BinaryTreeNode<T> *_right;
BinaryTreeNode(const T&x)
:_data(x)
, _left(NULL)
, _right(NULL)
{}
};
template <class T>
class BinaryTree
{
protected:
BinaryTreeNode<T> *_root;
BinaryTreeNode<T> *_creattree(const T a[], size_t size, size_t &index, T invalid)
{
BinaryTreeNode<T> * root = NULL;
if (index < size && a[index] != invalid)
{
root = new BinaryTreeNode<T>(a[index]);
root->_left = _creattree(a, size, ++index, invalid);
root->_right = _creattree(a, size, ++index, invalid);
}
return root;
}
void _prevorder(const BinaryTreeNode<T> *root)
{
if (root == NULL)
return;
cout << root->_data << " ";
_prevorder(root->_left);
_prevorder(root->_right);*/
}
void _inorder(const BinaryTreeNode<T> *root)
{
if (root == NULL)
return;
_inorder(root->_left);
cout << root->_data<<" ";
_inorder(root->_right);
}
void _postorder(const BinaryTreeNode<T> *root)
{
if (root == NULL)
return;
_postorder(root->_left);
_postorder(root->_right);
cout << root->_data << " ";
}
size_t _leafsize(const BinaryTreeNode<T> *root)
{
if (root == NULL)
return 0;
if (root->_left == NULL && root->_right == NULL)
return 1;
return _leafsize(root->_left) + _leafsize(root->_right);
}
size_t _size(const BinaryTreeNode<T> *root)
{
if (root == NULL)
return 0;
return _size(root->_left) + _size(root->_right) + 1;
}
size_t _Depth(const BinaryTreeNode<T> *root)
{
if (root == NULL)
return 0;
int left = _Depth(root->_left);
int right = _Depth(root->_right);
return left > right ? left + 1 : right + 1;
}
public:
BinaryTree(T const*a = "", size_t size = 0)
{
size_t index = 0;
_root = _creattree(a, size, index, '#');
}
void prevorder()
{
_prevorder(_root);
}
void inorder()
{
_inorder(_root);
}
void postorder()
{
_postorder(_root);
}
size_t size()
{
int count = _size(_root);
return count;
}
size_t leafsize()
{
int count = _leafsize(_root);
return count;
}
size_t Depth()
{
int depth = _Depth(_root);
return depth;
}
};
void test()
{
BinaryTree<char> b("12#3##45#6#7##8", 15);
/*b.levelorder();*/
/*BinaryTree<char> b1;
b1 = b;*/
/*cout<<b.Depth();*/
/*cout << b.size();*/
b.postorder();
/*cout << b.leafsize();*/
}
int main()
{
test();
getchar();
return 0;
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。