BFS in binary tree

前端 未结 3 1489
我在风中等你
我在风中等你 2021-02-10 10:38

I\'m trying to write the codes for breadth-first search in binary tree. I\'ve stored all the data in a queue, but I can\'t figure out how to travel to all nodes and consume all

3条回答
  •  我在风中等你
    2021-02-10 10:57

    A BFS can be easily written without recursion. Just use a queue to order your expansions:

    void BFS(btree *start)
    {
        std::deque q;
        q.push_back(start);
        while (q.size() != 0)
        {
            btree *next = q.front();
            // you may want to print the current node here or do other processing
            q.pop_front();
            if (next->left)
                q.push_back(next->left);
            if (next->right)
                q.push_back(next->right);
        }
    }
    

    The key is that you don't need to traverse the tree recursively; you just let your data structure handle the order in which you visit nodes.

    Note that I'm using the C++ deque here, but anything that lets you put items on the back and get them from the front will work fine.

提交回复
热议问题