您的位置:首页 > 其它

二叉树的层序遍历(非递归,借用队列实现)

2017-07-21 19:50 375 查看
1.【基础题】–实现一颗二叉树的层序遍历。

hljs cpp">#include<cassert>
#include<queue>
using namespace std;
template<class T>
struct  TreeNode
{
T data;
TreeNode* left;
TreeNode* right;
TreeNode(const T& x=T())
:data(x)
,left(NULL)
,right(NULL)
{}
};
template<class T>
class BinaryTree
{
typedef TreeNode<T> Node;
public:
BinaryTree(const T* arr,T invalid,int sz)//有参构造函数
{
assert(arr);
int index=0;
_root=BuildTree(arr,invalid,sz,index);
}
void SeqOrder()//层序遍历打印
{
assert(_root);
_SeqOrder(_root);
}
protected:
void _SeqOrder(Node* root)
{
assert(root);
queue<Node*> q;
q.push(root);
while (!q.empty())
{
cout<<q.front()->data<<" ";
if (q.front()->left)
{
q.push(q.front()->left);
}
if (q.front()->right)
{
q.push(q.front()->right);
}
q.pop();
}
}
Node* BuildTree(const T*arr,T& invalid,int sz, int& index)//前序遍历建树
{
assert(arr);
if (index<sz && arr[index]!=invalid)
{
Node* root=new Node(arr[index]);
root->left=BuildTree(arr,invalid,sz,++index);
root->right=BuildTree(arr,invalid,sz,++index);
return root;
}
return NULL;
}
protected:
Node* _root;

};
int main()
{
int arr[]={1, 2, 3, '#', '#', 4, '#' , '#', 5, 6};
int sz=sizeof(arr)/sizeof(arr[0]);
BinaryTree<int>  b(arr,'#',sz);//1 2 5 3 4 6
b.SeqOrder();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐