Reputation:
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* left_child;
Node* right_child;
Node(int x){
data = x;
left_child = NULL;
right_child = NULL;
}
};
class BST{
public:
//Initially root is null
Node* root = NULL;
void insert(Node* node, int data){
if(node == NULL){
node = new Node(data);
return;
}
if(data < node->data){
insert(node->left_child,data);
}
else if(data > node->data){
insert(node->right_child,data);
}
}
void just_insert(int data){
insert(root,data);
}
void print(Node* node){
if(node == NULL){
return;
}
cout<<node->data<<" ";
print(node->left_child);
print(node->right_child);
}
void just_print(){
print(root);
}
};
int main() {
//For fast IO
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,x;
cin>>n;
BST bst = BST();
for(int i=0; i<n; i++){
cin>>x;
bst.just_insert(x);
}
bst.just_print();
return 0;
}
What is wrong with this implementation of BST ? I am giving 8 values as input: 8 3 5 1 6 8 7 2 4 But when I invoke the print function. I do not get any output. Am I missing out on some pointer logic ? The insert function goes recursively down the tree, to find a place to insert the value The print function also works recursively.
Upvotes: 1
Views: 4681
Reputation: 409136
Lets take a look at these lines from the insert
function:
if(node == NULL){
node = new Node(data);
return;
}
The problem here is that the argument node
is passed by value and is like any other local variable, and like any other local variable it will go out of scope once the function returns, and all changes to the variable will be lost.
What you need is to pass the pointer by reference, like
void insert(Node*& node, int data){ ... }
// ^
// Note ampersand here
Upvotes: 4
Reputation: 1310
You never assign to root in your BST class because your assignment to node in the insert class is not visible outside the insert function. You can fix this by passing the Node pointer by reference to the insert function:
void insert(Node*& node, int data)
Upvotes: 1