I would like to implement a BST in C++, but I found that the integer variable "val" I pass in the constructor "Node()" seem not to work properly.
P.S. I am a totally newbie to this language, and here is my code
#include<iostream>
using namespace std;
class Node{
public:
int val;
Node *left;
Node *right;
// the constructor
Node(int val){
val = val;
left = nullptr;
right = nullptr;
}
};
class BST{
public:
Node *root;
BST(){
root = nullptr;
}
void insert(int val);
};
void BST::insert(int val){
if (root == nullptr){
root = new Node(val);
cout << root->val << endl; // output: 40580256(this number changes every time I run the code)
delete root;
};
if (root->val == val){
cout<<"The value: " << val << " is duplicated!" << endl;
}
}
int main() {
BST bst;
Node a = Node(10); // output: 8
cout << a.val << endl;;
bst.insert(8);
return 0;
}
It only works when I directly assign the variable "val" to root.val instead of using constructor to assign.
>Solution :
The reason why you’re having a problem is outlined in the comments, but, stylistically, it’s better to do this:
class Node{
public:
int val;
Node *left = nullptr;
Node *right = nullptr;
// the constructor
Node(int val) : val (val) { }
};
Now, nothing can go wrong.