Joshua
Joshua

Reputation: 4320

Recursively output a binary tree in ascending order

My current implementation of how to output my binary tree is getting me an error in g++, along the lines of

Conditional jump or move depends on uninitialised value(s)

My current implementation is:

void Foo::output(ostream &s, const Node *p)
{
    if( p )
    {
        output( s , p -> left );

        s << p -> info; 

        output( s , p -> right );
    }
}

The Node is a basic struct, with a left and right pointer, and an integer info variable.

the ostream is just cout

The error message is very straight forward, it doesn't like that I let it "run off".

My question is twofold:

  1. Why is this improper? Nothing is being changed, I don't know what it can hurt.
  2. What is the proper way to do this?

Thanks

Upvotes: 4

Views: 1789

Answers (1)

parapura rajkumar
parapura rajkumar

Reputation: 24423

Basically it means that some Node objects do not have left and right initialized to null.

Typically it is a good idea to define your node something like this

class Node
{
    int info;
    Node* left;
    Node* right;

public:

    Node( int infoin , Node* leftin = NULL , Node* rightin = NULL )
     : info(infoin) , left(leftin) , right(rightin) {}

}

This way if left and right nodes are not known at construction time , they are set to null.

And if they are indeed known at construction of Node you don't pay the penalty of setting right and left to null and then to something else

Upvotes: 6

Related Questions