level order traversal

So I'm trying to implement level order traversal for a binary tree off the top of my head. I feel like I am missing a return statement but is it absolutely necessary to have a return statement in a recursive function?

And is it okay that it took me about an hour to do this? I think I'm still trying to wrap my head around recursion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void BTree::level(Node * n)
{
    if(root == nullptr)
    {
        cout << "Tree is empty" << endl;
    }
    else{
        if(order.empty())
        {
            order.push(n);
            return level(n);
        }
        else
        {
            if(n->left != nullptr)
            {
                order.push(n->left);
            }
            if(n->right != nullptr)
            {
                order.push(n->right);
            }
            cout << order.front()->data << " ";
            order.pop();
            if(!order.empty())
            {
                level(order.front());
            }
        }
    }
}


I know I can do this

1
2
3
4
            if(!order.empty())
            {
                return level(order.front());
            }


but does this change anything?

This prints out correctly but with c++ I'm never sure.
Last edited on
Well, your function is void, so you can just let it end without returning anything.
So it's okay to do something recursive without having a return statement? I'm just concerned with memory here. So once the function ends the stack is released right?

Memory on the heap is the one I should be concerned about manually freeing?
Last edited on
So it's okay to do something recursive without having a return statement?
It is okay as long as your function is declared as returning nothing (void).

As soon as function ends all automatic variables are destroyed. return statement does not make a difference here. But if your function does return something and you did not place anything on stack (by return statement), then you have problems.
Awesome that clears up everything. Thanks MiiNiPaa
Topic archived. No new replies allowed.