0

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 ?       
2
Contributors
1
Reply
8
Views
3 Years
Discussion Span
Last Post by rubberman
0

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 by rubberman

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.