In function :

node* insert_in_tree(int number,node* p_tree) {

   if(p_tree == 0) {

    node* newNode = new node;
    newNode->num = number;
    newNode->p_left = 0;
    newNode->p_right = 0;
    return newNode;

    }

    if(number < p_tree->num) {

     p_tree->p_left = insert_in_tree(number,p_tree->p_left);

     }

     else {

        p_tree->p_right = insert_in_tree(number,p_tree->p_right);

     }

      return p_tree; // refering to this

 }

        in return p_tree is it returning newly created node, or a root node ?       

It depends upon your intention. Normally in recursive functions you would do this (assuming you don't want duplicate numbers):

node* insert_in_tree(int number,node* p_tree)
{
    if(p_tree == 0)
    {
        p_tree = new node;
        p_tree->num = number;
        p_tree->p_left = 0;
        p_tree->p_right = 0;
    }
    else if(number < p_tree->num)
    {
        p_tree->p_left = insert_in_tree(number,p_tree->p_left);
    }
    else if (number > p_tree->num)
    {
        p_tree->p_right = insert_in_tree(number,p_tree->p_right);
    }
    return p_tree; // refering to this
}

To determine if this is correct, I would have to see the rest of your code. Note that these changes allow you to keep to the optimal "1 return point per function". It also may allow the compiler to optimize the code a bit better.

Edited 2 Years Ago by rubberman

This article has been dead for over six months. Start a new discussion instead.