lundi 8 octobre 2018

Pointer to a new node in a Binary Tree

I was solving problem of insertion of node in a binary tree. I have the following doubts:

1) If we are inserting a node then we should return a pointer pointing to that node as then only we will be able to access the node, right?

2) Then here why are we returning root? We must return root->left or root->right accordingly, where am I wrong?

struct node* insert(struct node* root, int data)
    {
        if (root == NULL)    //If the tree is empty, return a new,single node
            return newNode(data);
        else
        {
            //Otherwise, recur down the tree 
            if (data <= root->data)
                root->left  = insert(root->left, data);
            else
                root->right = insert(root->right, data);
            return root;
        }
    }

3) Is this root which the above code returns the changed one from what it was previously due to recursion?

Aucun commentaire:

Enregistrer un commentaire