二叉树层序遍历的原理如图所示:
实现层序遍历的代码:
#include<iostream>
#include<queue>
using namespace std;
template <class T>
struct BinaryTreeNode
{
T* _data;
BinaryTreeNode<T>* _left;
BinaryTreeNode<T>* _right;
BinaryTreeNode(const T&)
:data(x)
, _left(NULL)
, _right(NULL)
{}
};
template <class T>
class BinaryTree
{
typedef BinaryTreeNode<T> Node;
public:
BinaryTree()
:_root(NULL)
{}
BinaryTree(T* a, size_t n, const& invalid )
{
size_t index = 0;
_root = _GreateTree(a, n, invalid index);
}
void LeveOrder()
{
return _LeveOrder(_root);
}
protected:
Node* _root;
protected:
Node* _GreateTree(T* a, size_t n, const T&invalid, size_t* index)
{
Node* root = NULL;
if (index < n&&a[index] != invalid)
{
root = new Node(a[index]);
root->_left = _GreateTree(a, n, invalid, ++index);
root->_right = _GreateTree(a, n, invalid, ++index);
}
return root;
}
void _LeveOrder()
{
queue<Node*> q;
if (_root)
{
q.push(_root);
}
while (!q.empty())
{
Node* front = q.front();
cont << front->_data << "";
q.pop();
if (front->_left)
{
q.push(front->_left);
}
if (front->_right)
{
q.push(front->_right)
}
}
}
};