美文网首页
BFS的分层(利用queue)

BFS的分层(利用queue)

作者: ClockworkTree | 来源:发表于2017-09-09 16:33 被阅读0次
  • 层序遍历二叉树,并且每层换行打印

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

vector<vector<int> > printTree(TreeNode* root) 
{
    vector<vector<int>> list;
    vector<int> inlist;
    queue<TreeNode *> 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<int> 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)

    层序遍历二叉树,并且每层换行打印 有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。给定二叉树的根结点root...

  • Binary Tree Level Order Traversa

    解題思路 : 就是基本的 BFS 思路 利用 queue 來完成 level order traversal 然後...

  • [127]word ladder

    以下使用双向bfs解法。利用two queue, two hashset. 同时采取check两个set的size...

  • 走迷宫(BFS例题)

    BFS例题---走迷宫 BFS对应数据结构queue BFS算法时间复杂度O(n^2) BFS算法不走走过的点 的...

  • 301 remove invalid parenthesis

    **BFS: ** remove i parenthesis and add to queue, when on...

  • bfs分层遍历

    intstep=1; while(!que.empty()){ intn=que.size(); while(n-...

  • LeetCode Invert Binary Tree(镜像)

    二叉树的镜像。 解法一(dfs recursive): 解法二(bfs queue): 注:解法二是层序遍历bfs...

  • leetcode-102. 二叉树的层次遍历 -BFS

    给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 BFS利用的结构是queue(先...

  • leetcode-打开转盘锁

    这道题估计在让我做一次,我还是做不出来的,想不到,且不好理解。 这道题用了BFS,广度优先搜索。利用queue队列...

  • LeetCode[5] - Binary Tree Right

    自己想了这个方法,有可能不是特别efficient.一个queue放普通的BFS。一个queue放level。同时...

网友评论

      本文标题:BFS的分层(利用queue)

      本文链接:https://www.haomeiwen.com/subject/ggnebttx.html