简体   繁体   中英

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;
 }

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM