Search code examples
c++binary-treetree-traversal

Traverse binary tree with unique_ptr child


I have some binary tree and I need to traverse it with queue. But the issue is that traversal requires "moving" object which I don't want to do.

Here is my routine:

struct bsp_node
{
    vec4 Plane;
    std::vector<polygon> Polygons;
    std::unique_ptr<bsp_node> Front;
    std::unique_ptr<bsp_node> Back;
};

uint32_t BSPGetIndexCount(const std::unique_ptr<bsp_node>& Tree)
{
    uint32_t Result = 0;
    std::queue<std::unique_ptr<bsp_node>&> BspQueue;
    BspQueue.push(Tree);

    uint32_t VertexIndex = 0;
    while(!BspQueue.empty())
    {
        std::unique_ptr<bsp_node>& Node = BspQueue.front();

        for(polygon Poly : Node->Polygons)
        {
            Result += 3;
        }

        BspQueue.pop();

        if(Tree->Front != nullptr)
        {
            BspQueue.push(Tree->Front);
        }

        if(Tree->Back != nullptr)
        {
            BspQueue.push(Tree->Back);
        }
    }

    return Result;
}

I guess, it should be trivial. But thanks for the help anyway.


Solution

  • BspQueue is a local variable, it cannot outlive Tree. Therefore you can use there raw pointers

    std::queue<bsp_node*> BspQueue;
    BspQueue.push(Tree.get());
    // ...
        bsp_nonde* Node = BspQueue.front().get();
    // ...
            BspQueue.push(Tree->Front.get());