Search code examples
c++binary-tree

Function for inserting a value in binary tree?


I have a function insert that is used to insert values into the Binary tree. But when I log out the value nothing is shown.

I'm aware of the insertion using member function.

The root node's value is not being updated?

Could someone tell me where I'm going wrong?

#include <iostream>

using namespace std;

class Node{

 public:
     int value;
     Node* left;
     Node* right;

     Node();

     Node(int data){
     value = data;
     left = NULL;
     right = NULL; 
    } 


};

void insert(Node* root , int val){
     if(root == NULL){
         root = new Node(val);
         return;
     }
    if(root->value > val)
         insert(root->left,val);
     else
        insert(root->right,val);


} 

int main()
   class Node* root  = NULL;
   insert(root,5);
   cout<<root->value;
 }

Solution

  • you are inserting position on the right place but the problem is you are not creating the link of your newly inserted node to it's parent.

    you can check this as reference!