Reputation: 13
I am trying to insert data in BST using cpp. I used the fallowing code:
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* left;
Node* right;
Node(int data){// Constructor...
data = data;
left = NULL;
right = NULL;
}
};
void Pre_Order_Trav(Node* Root){
if(Root==0) return;
cout << Root->data << " ";
Pre_Order_Trav(Root->left);
Pre_Order_Trav(Root->right);
}
Node* Get_New_Node(int data){
Node* temp;
temp = new Node(data);
//temp-> data = data; *******************************Watch Here****************
temp->left = NULL;
temp->right = NULL;
return temp;
}
Node* Insert(Node* Root,int data){
//cout << "Inserting: " << data<<"\n";
if(Root == NULL){
Root = Get_New_Node(data);
}
else if(data <= Root->data){
Root->left = Insert(Root->left,data);
}
else{
Root->right = Insert(Root->right,data);
}
return Root;
}
int main(){
int n,x;
//cout << "Enter the size of data: ";
//cin >> n;
cout << "\n";
cout << "Enter data: ";
Node* Root = NULL;
Root= Insert(Root,11);
while(cin >>x) Insert(Root,x);
cout << "\n";
Pre_Order_Trav(Root);
}
Node class has a constructor which assigns the given data to data and NULL to left and right.
When the "Watch Here" line is commented I am not able to traverse the tree, but when it is uncommented I was able to traverse successfully. Isn't temp = new Node(data)
is same as temp->data = data
?
Upvotes: -1
Views: 48
Reputation: 75062
The line
data = data;
in the constructor is assigning the argument data
to the argument data
, virtually doing nothing.
It should be
this->data = data;
to initialize the member variable data
.
Upvotes: 1