BFS的分层(利用queue)

  • 层序遍历二叉树,并且每层换行打印

有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。
给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。
https://www.nowcoder.com/questionTerminal/316469a26b5048c984881e761692a382

vector > printTree(TreeNode* root) 
{
    vector> list;
    vector inlist;
    queue q;
    if (root == NULL) return list;
    q.push(root);
    TreeNode * last = root;
    while (!q.empty())
    {
        root = q.front();
        q.pop();
        if (root->left != NULL) q.push(root->left);
     if (root->right != NULL) q.push(root->right);
        inlist.push_back(root->val);
        if (last == root)
        {
            last = q.back();
            list.push_back(inlist);
            inlist.clear();
        }
    }
    return list;
}
  • 分层遍历打印邻接表

void BFSprint(LGraph g, void(Visit)(Vertex),int v)
{
    queue q;
    q.push(v);
    Visited[v] = true;
    int last = v;
    AdjVNode * temp = NULL;
    while (!q.empty())
    {
        v =q.front() ;
        q.pop();
        Visit(v);
        temp = g->G[v].FirstEdge;
        while (temp!=NULL)
        {
            if (Visited[temp->AdjV] == false)
            {
                q.push(temp->AdjV);
                Visited[temp->AdjV] = true;
            }
            temp = temp->Next;
        }
        if (last == v&&!q.empty())
        {
            last = q.back();
            cout << endl;
        }
    }


你可能感兴趣的:(BFS的分层(利用queue))