您的位置:首页 > 其它

二叉树的创建,前序,中序,后序,层序遍历

2017-04-27 23:49 459 查看
二叉树(binary tree)是另一种树形结构,它的特点是每个节点至多有两颗子树,并且其子树有左右之分,并且顺序不能颠倒。

主要用递归的思想完成创建,遍历等操作。



#include <iostream>
using namespace std;
#include <string>
#include <queue>

template <typename T>
struct TreeNode{
TreeNode(const T& value)
:_value(value)
,_pLeft(NULL)
,_pRight(NULL)
{}
TreeNode<T> *_pLeft;
TreeNode<T> *_pRight;
T _value;
};

template <typename T>
class BinaryTree{
typedef TreeNode<T> Node;
public:
BinaryTree()
:_pRoot(NULL)
{}

BinaryTree(const T* arr, const T& invalied)  //传入一个顺序为前序的数组,invalied意味节点为NULL
{
int index = 0;
createTree(arr, _pRoot, strlen(arr), invalied, index);
}

BinaryTree(const BinaryTree<T>& t)
{
_pRoot = _CopyTree(t._pRoot);
}

BinaryTree<T>& operator=(const BinaryTree<T>& t)
{
_DestroyTree(_pRoot);
_pRoot = _CopyTree(t._pRoot);
return *this;
}

void PreOrder()  //前序访问
{
_PreOrder(_pRoot);
cout<<"end"<<endl;
}

void InOrder() //中序访问
{
_InOrder(_pRoot);
cout<<"end"<<endl;
}

void PostOrder() //后序访问
{
_PostOrder(_pRoot);
cout<<"end"<<endl;
}

void LeverOrder() //层序访问
{
queue<Node*> q;
if (_pRoot)
{
q.push(_pRoot);
_LeverOrder(_pRoot, q);
}
}

~BinaryTree()
{
_DestroyTree(_pRoot);
}

private:
void createTree(const T* arr,Node* &proot ,size_t size,
const T& invalied, int& index)
{
if (index < size && arr[index] != invalied)
{
proot = new Node(arr[index]);
createTree(arr, proot->_pLeft,size, invalied, ++index);
createTree(arr, proot->_pRight,size, invalied, ++index);
}
}

Node *_CopyTree(Node* proot)
{
if (proot)
{
Node *temp = new Node(proot->_value);
temp ->_pLeft = _CopyTree(proot->_pLeft);
temp ->_pRight = _CopyTree(proot->_pRight);
return temp;
}
return NULL;
}

void _DestroyTree(Node *&proot)
{
if (proot)
{
_DestroyTree(proot->_pLeft);
_DestroyTree(proot->_pRight);
delete proot;
proot = NULL;
}
}

void _PreOrder( Node* proot)
{
if (proot)
{
cout<<proot->_value<<"->";
_PreOrder(proot->_pLeft);
_PreOrder(proot->_pRight);
}
}

void _InOrder(Node *proot)
{
if (proot)
{
_InOrder(proot->_pLeft);
cout<<proot->_value<<"->";
_InOrder(proot->_pRight);
}
}

void _PostOrder(Node *proot)
{
if (proot)
{
_PostOrder(proot->_pLeft);
_PostOrder(proot->_pRight);
cout<<proot->_value<<"->";
}
}

void _LeverOrder(Node *proot, queue<Node*>& q)
{
while (!q.empty())
{
Node* temp = q.front();
cout<<temp->_value<<"->";
q.pop();
if (temp->_pLeft)
q.push(temp->_pLeft);
if (temp->_pRight)
q.push(temp->_pRight);
}
cout<<"end"<<endl;
}

private:
Node *_pRoot;
};

int main()
{
char* str= "124##57##8##3#6";
BinaryTree<char> tree(str,'#');
tree.PreOrder();
tree.InOrder();
tree.PostOrder();
tree.LeverOrder();
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 遍历 递归
相关文章推荐