Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Insert in Binary Search Tree

+4 votes
asked Oct 19 by Aki Ha (160 points)

When I print the entire tree it prints the values 30 and 50, but I have recently changed it to have two pointers: Node *a, *b; a = insertNode(NULL, 1) b = insertNode(a, 2) However the b pointer just points to the root node - I believe this is an issue in the insertNode function in what I return. I want to return the newly added leaf node not the original root node, but I am unsure of how to do this.

#include<stdio.h>
    #include<stdlib.h>
    #include<assert.h>
    
    typedef struct _Node{
        int data;
        struct _Node *left, *right;
    }Node;
    
    Node *insertNode(Node *root, int value){
        if(root == NULL){
            Node *temp = (Node*)malloc(sizeof(Node));
            temp->data = value;
            temp->left = temp->right = NULL;
            return temp;
        }
        if(root->data < value){
            root->right = insertNode(root->right, value);
        }
        else if(root->data > value){
            root->left = insertNode(root->left, value);
        }
        else{
            
        }
        return root;
    }  
    
   
void printNode( Node * pnode )
{
   if( pnode )
   {
       printf( "node at %p : left=%p, right=%p, data=%d\n",
           pnode, pnode->left, pnode->right, pnode->data );
       if( pnode->left )
           printNode( pnode->left );
       if( pnode->right )
           printNode( pnode->right );
   }
   else
       printf( "node is null\n" );
    
    int main(){
        Node *a;
    
        a = insertNode(NULL, 30);
        a = insertNode(a, 50);
        b = insertNode(a, 70);        
        b = insertNode(a, 80);
        b = insertNode(a, 90);
        printNode(b); 
//I only want to print out 70,80,90 rather than the whole tree 30,50,70,80,90
    }

1 Answer

0 votes
answered Oct 20 by Peter Minarik (63,140 points)
edited Oct 20 by Peter Minarik

I think what you need is this:

    if (root->data < value)
    {
        return root->right = insertNode(root->right, value);
    }
    else if(root->data > value)
    {
        return root->left = insertNode(root->left, value);
    }

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...