could you please tell me why the call of the method binaryTree.Exists(5); says that "5 doesn't exist in the binary tree"? when debugging, it's like when trying to access the node where 5 is inserted doesn't exist anymore. i don't see why. thank you!!!
#include <iostream>
using namespace std;
class Node
{
private:
int _value;
Node* left;
Node* right;
public:
Node(int value):_value(value), left(NULL), right(NULL)
{
}
Node* returnLeftChild()
{
return left;
}
Node* returnRightChild()
{
return right;
}
void setLeftChild(Node* l)
{
left=l;
}
void setRightChild(Node* r)
{
right=r;
}
int getValue()
{
return _value;
}
};
class BinaryTree
{
private:
Node parent;
void AddToOneTree(Node* parent, int value)
{
if (value==parent->getValue())
{
return;
}
if (value>parent->getValue())
{
if (parent->returnRightChild()==NULL)
{
Node newNode(value);
parent->setRightChild(&newNode);
return;
}
else
{
AddToOneTree(parent->returnRightChild(), value);
}
}
if (value<parent->getValue())
{
if (parent->returnLeftChild()==NULL)
{
Node newNode(value);
parent->setLeftChild(&newNode);
return;
}
else
{
AddToOneTree(parent->returnLeftChild(), value);
}
}
}
void LookForValue(Node* parent, int value, bool found)
{
if (value>parent->getValue())
{
if (parent->returnRightChild()!=NULL)
{
if (parent->returnRightChild()->getValue()==value)
{
found= true;
goto HERE;
}
else
{
LookForValue(parent->returnRightChild(), value, found);
}
}
}
else if (value<parent->getValue())
{
if (parent->returnLeftChild()!=NULL)
{
if (parent->returnLeftChild()->getValue()==value)
{
found= true;
goto HERE;
}
else
{
LookForValue(parent->returnLeftChild(), value, found);
}
}
}
HERE:;
}
public:
BinaryTree(int parentValue):parent(parentValue)
{
}
void Add(int value)
{
AddToOneTree(&parent, value);
}
void Exists(int value)
{
bool found = false;
if (parent.getValue()==value)
{
cout << value << " exists in the Binary Tree." << endl;
}
else{
LookForValue(&parent, value, found);
if (found)
{
cout << value << " exists in the Binary Tree." << endl;
}else
{
cout << value << " doesn't exist in the Binary Tree." << endl;
}
}
}
};
int main()
{
BinaryTree binaryTree(9);
binaryTree.Add(5);
binaryTree.Add(5);
binaryTree.Exists(9);
binaryTree.Exists(5);
}