I am having trouble with this. I believe I have found where the problem is with the random couts in the functions. When a node is added it keeps getting added to root node. It won't become a new node. What am I doing wrong? Thanks for any help offered.
Code:
#include <iostream>
using namespace std;
class Node
{
public:
Node(int v);
~Node();
int value;
Node* left;
Node *right;
};
Node::Node(int v)
{
value = v;
left = NULL;
right = NULL;
}
Node::~Node() {}
class BinaryTree
{
public:
BinaryTree();
~BinaryTree();
void add(int i);
void display();
void clear();
private:
Node* root;
void removeNode(Node* n);
void displayValue(Node* n);
void insertNode(Node* n, int v);
};
BinaryTree::BinaryTree()
{
root = NULL;
}
BinaryTree::~BinaryTree()
{
removeNode(root);
}
void BinaryTree::removeNode(Node* n)
{
if (n)
{
removeNode(n->left);
removeNode(n->right);
delete n;
}
}
void BinaryTree::clear()
{
removeNode(root);
}
void BinaryTree::display()
{
cout << "Values: ";
displayValue(root);
cout << endl;
}
void BinaryTree::displayValue(Node* n)
{
if (n)
{
if (n->left)
displayValue(n->left);
if (n->right)
displayValue(n->right);
cout << n->value << ", ";
}
}
void BinaryTree::add(int i)
{
if (root)
cout << "root is not null" <<endl;
else
cout << "root is null" << endl;
insertNode(root, i);
}
void BinaryTree::insertNode(Node* n, int v)
{
if (n)
{
if (v < n->value)
insertNode(n->left, v);
else
insertNode(n->right, v);
cout << "branch added" << endl;
}
else
{
n = new Node(v);
cout << "leaf added" << endl;
}
}
int main()
{
BinaryTree Tree;
int response = 0;
int value;
while (response != 4)
{
cout << "1. Add A Number." << endl;
cout << "2. Display Values." << endl;
cout << "3. Clear Tree." << endl;
cout << "4. Exit." << endl;
cin >> response;
if (response == 1)
{
cout << "Value to add: ";
cin >> value;
Tree.add(value);
}
else if (response == 2)
{
Tree.display();
}
else if (response == 3)
{
Tree.clear();
}
cout << " ----------------------------- " << endl;
}
cin.get();
return 0;
}