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

1.【基础题】–实现一颗二叉树的层序遍历。

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值