-1

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;
 }
  • 2
    You pass `Node* root` to `insert()` i.e. the pointer by value. Hence, changes to `root` get lost if you return from `insert()`. Change it to `Node*& root` to pass it by reference and achieve that the "original" pointer is changed (instead of a local copy). – Scheff's Cat Jun 26 '21 at 15:09
  • FYI: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/7478597) In a debugger, you should have seen that the modified `root` is lost once you return from `insert()`. Debugging is an essential technique concerning software development. – Scheff's Cat Jun 26 '21 at 15:12
  • 1
    I, tried debugging and noticed that root was 0x00 the whole time. I couldn't make out something was wrong but didn't know how to approach it. – rohith raju Jun 26 '21 at 15:15
  • Yeah, I was aware that the debugger could have shown the problem but, of course, doesn't offer the solution... ;-) – Scheff's Cat Jun 26 '21 at 15:18

1 Answers1

1

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!

Papai from BEKOAIL
  • 1,469
  • 1
  • 11
  • 17