Reputation: 717
I am writing a binary tree (for only numbers zero or larger) in C++ and for some reason all the values but the head seem to be zero (when I add an element) and I am not sure why that is happening. This seems like it would be rather obvious but I've been staring at this for 2 hours and can't seem to figure out what is happening.
Here is my BinaryTree.cpp:
#include "BinaryTree.h"
BinaryTree::Node::Node(){
lChild = NULL;
rChild = NULL;
data = -1;
}
BinaryTree::Node::Node(int data){
lChild = NULL;
rChild = NULL;
data = data;
}
BinaryTree::BinaryTree(){
head = new Node();
}
BinaryTree::BinaryTree(int num){
head = new Node(num);
}
void BinaryTree::addElement(int data){
addElement(data, head);
}
void BinaryTree::addElement(int data, Node * node){
if( node -> data != -1){
if(node -> data > data){
if(node -> lChild){
addElement(data, node -> lChild);
}
else{
node ->lChild = new Node(data);
}
}
else{
if(node -> rChild){
addElement(data, node -> rChild);
}
else{
node -> rChild = new Node(data);
}
}
}
else{
node -> data = data;
}
}
Here is my BinaryTree.h:
#ifndef __ConnectTree__BinaryTree__
#define __ConnectTree__BinaryTree__
#include <iostream>
class BinaryTree{
private:
class Node{
public:
int data;
Node * lChild;
Node * rChild;
Node();
Node(int data);
};
Node * head;
void addElement(int num, Node * node);
public:
BinaryTree();
BinaryTree(int num);
void addElement(int num);
};
#endif /* defined(__ConnectTree__BinaryTree__) */
Here is my main.cpp where I create a Binary Tree object and insert objects into the tree.
#include <iostream>
#include "BinaryTree.h"
int main(int argc, const char * argv[])
{
// insert code here...
std::cout << "Hello, World!\n";
BinaryTree t;
t.addElement(4);
t.addElement(10);
t.addElement(11);
t.addElement(9);
t.addElement(2);
t.addElement(1);
t.addElement(3);
return 0;
}
Upvotes: 2
Views: 159
Reputation: 2830
The problem is with this line in BinaryTree::Node::Node(int data) implementation:
data = data;
If you still can't find, I'll edit my answer to let you know exact problem.
Upvotes: 2