Recursive Function Error: "-var-create: unable to create variable object" - c++

I made a Binary Tree for storing 2 chars 'R' and 'B'. The inserting and printing functions work fine but while executing searching function, the pointer variable gives the error -var-create: unable to create variable object when watched under VS code's debugger tool.
Node Struct Code:
struct Node
{
Node * left;
Node * right;
char value;
bool endSeq = false;
};
BST's Search Functions:
bool search(string k)
{
int len = k.length();
bool found = false;
searchHelper(root, k, len, found);
if(found)
{
return true;
}
return false;
}
Node * searchHelper(Node * p, string k, int & len, bool & found)
{
if(p == NULL)
{
return NULL;
}
else if(len == 0)
{
if(p->endSeq)
{
found = true;
}
return p;
}
else if(k[0] < p->value || (k[0] == 'B' && k[0] == p->value))
{
string kNew = k.substr(1, --len);
if(p->endSeq)
{
found = true;
}
else
{
insertHelper(p->left, kNew, len);
}
}
else if(k[0] > p->value || (k[0] == 'R' && k[0] == p->value))
{
string kNew = k.substr(1, --len);
if(p->endSeq)
{
found = true;
}
else
{
insertHelper(p->right, kNew, len);
}
}
return p;
}

Theres a problem in your code. You have made a wrong recursive call. Instead of calling insertHelper you should call searchHelper

Related

Why does this code run for VS but not gcc/g++?

I'm trying to implement a Red Black Tree using VS 2019 as my IDE. It seems to work in VS but when I try to compile and run using anything else, it results in a seg fault whenever my insert function is called more than once. (I've tried online compilers and sending it to a friend) I'm stuck as I don't know where to start trying to fix my error. I've heard that VS handles dynamic memory differently but I'm not too sure.
Below is my rotate, BST insert and insert functions.
#include <iostream>
#include <vector>
// default constructor
// creates empty tree, root is nullptr
class NodeT
{
public:
// public variables
double key;
double value;
NodeT* left;
NodeT* right;
NodeT* parent;
bool isBlack;
// constructors
NodeT()
{
key = 0;
value = 0;
left = nullptr;
right = nullptr;
parent = nullptr;
isBlack = false;
}
NodeT(double keyset, double valueset, bool isBlackset)
{
key = keyset;
value = valueset;
left = nullptr;
right = nullptr;
parent = nullptr;
isBlack = isBlackset;
}
};
class RedBlackTree
{
public:
// default constructor, sets all to null
RedBlackTree();
// insert
// inserts the first parameter key, and value second parameter into the tree
// returns true if done, false if there are duplicates, dont insert
bool insert(double insert_key, double insert_value);
public:
NodeT* root;
void leftrotate(NodeT* to_rotate);
void rightrotate(NodeT* to_rotate);
bool bstinsert(NodeT* insert);
};
RedBlackTree::RedBlackTree()
{
root = nullptr;
}
void RedBlackTree::leftrotate(NodeT* to_rotate)
{
NodeT* new_parent = nullptr;
new_parent = to_rotate->right;
to_rotate->right = new_parent->left;
if (new_parent->left != nullptr)
{
new_parent->left->parent = to_rotate;
}
new_parent->parent = to_rotate->parent;
if (to_rotate->parent == nullptr)
{
root = new_parent;
}
else if (to_rotate == to_rotate->parent->left)
{
to_rotate->parent->left = new_parent;
}
else
{
to_rotate->parent->right = new_parent;
}
new_parent->left = to_rotate;
to_rotate->parent = new_parent;
}
void RedBlackTree::rightrotate(NodeT* to_rotate)
{
NodeT* new_parent = to_rotate->left;
to_rotate->left = new_parent->right;
if (new_parent->right != nullptr)
{
new_parent->right->parent = to_rotate;
}
new_parent->parent = to_rotate->parent;
if (to_rotate->parent == nullptr)
{
root = new_parent;
}
else if (to_rotate == to_rotate->parent->right)
{
to_rotate->parent->right = new_parent;
}
else
{
to_rotate->parent->left = new_parent;
}
new_parent->right = to_rotate;
to_rotate->parent = new_parent;
}
bool RedBlackTree::bstinsert(NodeT* insert)
{
NodeT* parent = root;
NodeT* search = root;
if (root == nullptr)
{
root = insert;
}
else
{
while (search != nullptr)
{
parent = search;
if (insert->key < parent->key)
{
search = parent->left;
}
else if (insert->key > parent->key)
{
search = parent->right;
}
else
{
return false;
}
}
if (insert->key < parent->key)
{
parent->left = insert;
insert->parent = parent;
return true;
}
else if(insert->key > parent->key)
{
parent->right = insert;
insert->parent = parent;
return true;
}
else
{
return false;
}
}
}
bool RedBlackTree::insert(double insert_key, double insert_value)
{
NodeT* y = nullptr;
NodeT* x = new NodeT(insert_key, insert_value, false);
bool dupe = bstinsert(x);
if (dupe == false)
{
return false;
}
while (x != root && x->parent->isBlack == false)
{
if (x->parent == x->parent->parent->left)
{
y = x->parent->parent->right;
if (y == nullptr || y->isBlack == true)
{
if (x == x->parent->right)
{
x = x->parent;
leftrotate(x);
}
x->parent->isBlack = true;
x->parent->parent->isBlack = false;
rightrotate(x->parent->parent);
}
else if (y->isBlack == false)
{
x->parent->isBlack = true;
y->isBlack = true;
x->parent->parent->isBlack = false;
x = x->parent->parent;
}
}
else
{
y = x->parent->parent->left;
if (y == nullptr || y->isBlack == true)
{
if (x == x->parent->left)
{
x = x->parent;
rightrotate(x);
}
x->parent->isBlack = true;
x->parent->parent->isBlack = false;
leftrotate(x->parent->parent);
}
else if (y->isBlack == false)
{
x->parent->isBlack = true;
y->isBlack = true;
x->parent->parent->isBlack = false;
x = x->parent->parent;
}
}
}
root->isBlack = true;
return true;
}
Calling this in main results in an seg fault except when in VS:
int main()
{
RedBlackTree test;
test.insert(47, 1);
test.insert(32, 2);
}
Thanks for taking the time to read this. Any help is appreciated.
There is at least one error that causes undefined behavior:
The RedBlackTree::bstinsert function fails to return a value when it is supposed to return a bool.
To verify this is the error, a line right before the end of the bstinsert function can be placed to verify that this is an error.
bool RedBlackTree::bstinsert(NodeT* insert)
{
NodeT* parent = root;
NodeT* search = root;
if (root == nullptr)
{
root = insert;
}
else
{
while (search != nullptr)
{
parent = search;
if (insert->key < parent->key)
{
search = parent->left;
}
else if (insert->key > parent->key)
{
search = parent->right;
}
else
{
return false;
}
}
if (insert->key < parent->key)
{
parent->left = insert;
insert->parent = parent;
return true;
}
else if (insert->key > parent->key)
{
parent->right = insert;
insert->parent = parent;
return true;
}
else
{
return false;
}
}
std::cout << "This is undefined behavior\n"; // <-- add this line
}
You will see that the std::cout line will be encountered to confirm that you are returning from bstinsert without returning a value.
Also, the compiler you're using (Visual Studio), would have given a warning to you about this issue. Something similar to this:
warning C4715: 'RedBlackTree::bstinsert': not all control paths return a value
You should not have ignored this warning.

How to check if a tree is a BST?

I have to check if a tree is a binary search tree. I'm doing this with an inorder traversal with a temporary array that collects the values. I have to check if the array is ascending order and if it is then I return true:
bool myisBST(Node* node, std::vector<int> v);
bool myisBST(Node* node)
{
return myisBST(node, std::vector<int>());
}
bool myisBST(Node* node, std::vector<int> v)
{
if (node)
{
if (node->left)
return myisBST(node->left, v);
v.push_back(node->data);
if (node->right)
return myisBST(node->right, v);
}
return std::is_sorted(v.begin(), v.end());
}
When binary tree is this:
50
/ \
25 75
/ \ / \
1 12 62 -99
As you can see, the -99 makes this not a binary search tree, but it is still returning true. Is there something wrong with my implementation?
Demo
Two problems:
In myisBST, you are passing v by value, not by reference, so when you pass the vector on recursively, the changes that are made to it don't change its value in the calling method. Simply change the function signature to bool myisBST(Node* node, std::vector<int>& v) to fix this.
The value you should be returning is whether the vector is sorted (as you do in the last line of your method), but instead you are returning prematurely by writing return myisBST(node->left, v); and return myisBST(node->right, v);. You're not actually interested in the return values of these methods; you're just using them to fill the vector inorder. Remove the return from both of these lines.
Following these two fixes, your method works.
First of all, you should probably pass the vector by reference or each recursive call will get a copy and thus the original vector will probably be empty.
Second, you don't even need to create the vector first and then do the check, you can just check the BST property at each node, i.e., the root must be bigger than the left child and smaller than the right child, e.g.,
bool isBST(const Node* root, vector<int>* v) {
if (!root) { return true; }
bool leftBST = true;
if (root->left) {
if (root->data > root->left->data) {
leftBST = isBST(root->left, v);
} else {
// the current node violates the BST precondition
return false;
}
}
// push the root
v->push_back(root->data);
// return false if left subtree is not a BST
if (!leftBST) return false;
if (root->right) {
if (root->data < root->right->data) {
// return whether or not the right subtree is a BST
return isBST(root->left, v);
} else {
// the current node violates the BST precondition
return false;
}
}
// everything good, this is a BST
return true;
}
C++ Program to check if tree is BST or not
struct Node
{
int data;
struct Node* left, *right;
};
bool IsBST(Node* ObjNode)
{
bool leftBST = false;
bool rightBST = false;
if( ObjNode->left != null && ObjNode-left < objNode->data)
{
leftBST = IsBST(ObjNode->left)
}
else if( ObjNode->left == null)
{
leftBST = true;
}
else if( ObjNode->left != null && ObjNode-left >= objNode->data)
{
leftBST = false;
}
if( ObjNode->left != null && ObjNode-left < objNode->data)
{
rightBST = IsBST(ObjNode->right)
}
else if( ObjNode->right == null)
{
rightBST = true;
}
else if( ObjNode->right != null && ObjNode-right >= objNode->data)
{
rightBST = false;
}
return (leftBST && rightBST );
}
In the previous solution, they are keeping a list of the inorder traversal, you really don't need it, you can keep checking with the last traversed element and keep moving forward.
Following solution is the fastest
class Solution {
int lastval = Integer.MIN_VALUE;
int count = 0;
public boolean isValidBST(TreeNode root) {
if(root == null) return true;
boolean left = isValidBST(root.left);
if(!left){
return false;
}
int rootVal = root.val;
if(rootVal == -2147483648 && count == 0 ){
rootVal = rootVal + 1;
}
if( rootVal <= lastval){
return false;
}
count ++;
lastval = root.val;
boolean right = isValidBST(root.right);
if(!right){
return false;
}
return true;
}
}

How to check if a binary tree remains AVL and maintain it?

I'm having some trouble with the creation of an AVL tree structure in C++ for a university project. So far, I managed to make simple add and delete functions, but here comes the problem! I 've seen some codes here where the checks are made in the add function directly, but I didn't want to copy the code. Is there a way to create a seperate function which does exactly this work? The thing I can't make work is how to make the program understand in which rotation case I have to go.
My code so far is this:
struct node
{
unsigned int target;
struct node *left;
struct node *right;
};
int ClassInvertedIndex::Height(struct node *toCheck)
{
int left, right;
if(toCheck == NULL)
return 0;
left = Height(toCheck->left);
right = Height(toCheck->right);
if(left > right)
return left+1;
else
return right+1;
}
void ClassInvertedIndex::maintainAVL(struct node *toCheck)
{
if(Height(toCheck->left)-Height(toCheck->right) == 2); //Left subtree problem.
if(Height(toCheck->right)-Height(toCheck->left) == 2); //Right subtree problem.
}
bool ClassInvertedIndex::addNode(unsigned int x)
{
return insideAdd(data, x);
}
bool ClassInvertedIndex::insideAdd(struct node *toAdd, unsigned int x)
{
if(toAdd == NULL)
{
toAdd = new struct node;
if(toAdd == NULL)
{
cout << "Could not allocate memory.";
return false;
}
toAdd->left = NULL;
toAdd->right = NULL;
toAdd->target = x;
return true;
}
else if(x < toAdd->target)
{
bool result;
result = insideAdd(toAdd->left, x);
if(result)
{
//maintainAVL(toAdd);
}
return result;
}
else if(x > toAdd->target)
{
bool result;
result = insideAdd(toAdd->right, x);
if(result)
{
//maintainAVL(toAdd);
}
return result;
}
else //x already exists.
{
return false;
}
}
So, in the maintainAVL method, what should I do to decide what rotation I need?

Access violation reading location 0x00000000 in binary search tree

Just showing how the node of the binary tree looks like. I'm not sure what is wrong but I have a feeling it has something to do with the function being private. How I can compare the private data so I can see if the value I am looking for is inside that node?
class binarytree
{
private:
class node
{
public:
int data;
node * left;
node * right;
node (int x)
{
data = x;
left=NULL;
right=NULL;
}
};
node * root;
This is how I insert the node
void insert(int x, node * &r)
{
if(r==NULL)
{
r= new node(x);
}
else
{
if(x < r->data)
{
//insert left
insert(x, r->left);
}
else
{
//insert right
insert(x, r->right);
}
}
}
Here is the part of the code that gives me trouble when I try to compare x to r->data the program crashes and gives me the error message " Access violation reading location 0x00000000"
void remove(int x, node * &r)
{
if(x == r->data)
{
if(r->right == NULL && r->left == NULL)
{
r = NULL;
}
else if(r->right == NULL && r->left != NULL)
{
r = r->left;
}
else if(r->right != NULL && r->left == NULL)
{
r = r->right;
}
else
{
node * temp;
temp =r;
r = r->left;
while(r->right != NULL)
{
r = r->right;
}
r->right = temp->right;
delete temp;
}
}
else if ( x < r->data)
{
remove(x, r->left);
}
else if (x > r->data)
{
remove(x , r->left);
}
}
This is where the functions are publicly. Then I call the private functions so I can manipulate the private tree.
public:
binarytree()
{
root = NULL;
}
~binarytree()
{
//tooo: write this
}
//return true if empty, false if not
bool empty()
{}
void insert(int x)
{
insert(x, root);
}
void remove(int x)
{
remove(x,root);
}
};
EDIT: Here is another function of the program that works but might be causing r to point to NULL.
int extractMin(node * &r)
{
if(r->left == NULL)
{
if(r->right == NULL)
{
return r->data;
}
else
{
int x = r->data;
r = r->right;
return x;
}
}
else
{
return extractMin(r->left);
}
}
Here is the new function to check to see if r is NULL
void remove(int x, node * &r)
{
if(r == NULL)
{
cout<<"why am I null?"<<endl;
}
else
{
if(x == r->data)
{
if(r->right == NULL && r->left == NULL)
{
r = NULL;
}
else if(r->right == NULL && r->left != NULL)
{
r = r->left;
}
else if(r->right != NULL && r->left == NULL)
{
r = r->right;
}
else
{
node * temp;
temp =r;
r = r->left;
while(r->right != NULL)
{
r = r->right;
}
r->right = temp->right;
delete temp;
}
}
else if ( x < r->data)
{
remove(x, r->left);
}
else if (x > r->data)
{
remove(x , r->left);
}
}
}
you should always check for NULL before trying to get to the inner members:
void remove(int x, node * &r)
{
if(r != NULL)
{
// Your code
}
}
you call to remove with r as NULL and then try to check r.Left. then here you have access violation
also i must ask, did any if this worked for you? specifically insert wont work this way.
try
void insert(int x, node * &r)
{
if(r==NULL)
{
r= new node(x);
}
else
{
if(x < r->data)
{
if(r->left != NULL)
{
//insert left
insert(x, r->left);
}
else
{
r->left = new node(x);
}
}
else
{
if(r->right != NULL)
{
//insert right
insert(x, r->right);
}
else
{
r->left = new node(x);
}
}
}
}
r is null somehow. You need to check if the r passed in is NULL, or check if the root is non-null, and call remove on children only if they exist.
Well it the error says, r is pointing to NULL when you try to derefference it.
So you have to make sure when you assign memmory to r it doesn't return NULL.
binarytree()
{
root = NULL;
}
void remove(int x)
{
remove(x,root);
}
In your case you are trying to derefference NULL (as the error says) This happens in your code when you are calling a remove before you have called an insert.
You simply should check at the beginning of remove for r isn't pointing to NULL.
Or even better, make sure you won't parse in r when its NULL.
You are comparing x to the root. When your tree is empty, root == nullptr. You should check to see if r == nullptr first, as in:
bool remove(int x, node * &r) {
if(!r) {
return false; // Indicate whether removal succeeded
}
//... etc.
}

Why is this C++ code producing a segmentation fault?

The code function that I'm specifically talking about is getCount(). There are several other functions that I haven't included here (such as finding the height of this binary tree and the total node count) which work just fine, with correct results. getCount() on the other hand produces segmentation fault except for the first node (the top, first node of the tree). Any ideas?
#include <string>
#include <algorithm>
#include <iostream>
class Word {
public:
std::string keyval;
long long count;
Word() {
keyval = "";
count = 0;
}
Word(std::string S) {
keyval = S;
count = 1;
}
};
class WordBST {
public:
Word node;
WordBST* left_child;
WordBST* right_child;
WordBST(std::string key);
void add(std::string key){
if (key == node.keyval){
node.count++;
}
else if (key < node.keyval){
if (left_child == NULL){
left_child = new WordBST(key);
}else {
left_child->add(key);
}
}else {
if (right_child == NULL){
right_child = new WordBST(key);
}else {
right_child->add(key);
}
}
}
long long getCount(std::string key){
if (key == node.keyval){
return (node.count);
}
else if (key < node.keyval){
left_child->getCount(key);
}else if(key > node.keyval){
right_child->getCount(key);
}else return 0;
/*else {
if (key < node.keyval){
left_child->getCount(key);
}else{
right_child->getCount(key);
}
}*/
}
};
WordBST::WordBST(std::string key) {
node = Word(key);
left_child = NULL;
right_child = NULL;
}
This is because you let your code run off the end without hitting a return statement.
long long getCount(std::string key){
if (key == node.keyval){
return (node.count);
} else if (left_child && key < node.keyval){
return left_child->getCount(key); // Added return
} else if(right_child && key > node.keyval){
return right_child->getCount(key); // Added return
}
return 0;
}
You also need to add null checks in more than one place throughout the code. Your add method has them, but your getCount does not.
I think you should write getCount() like this:
long long getCount(std::string key){
if (key == node.keyval){
return (node.count);
}
else if (key < node.keyval && left_child != NULL){
return left_child->getCount(key);
}else if(key > node.keyval && right_child != NULL){
return right_child->getCount(key);
}else return 0;
}
You do not check to see if the children of your node exist before calling their methods.