I am new to C++. Originally a java developer
I created a binarytree in C++. It added methods to add values and prints values .
But somewhere I have done some mistake and a pointer is pointing to itself in the printNode() method
I am pasting my code below. Can anyone help me in figuring out the mistake I made
main.cpp
#include <iostream>
#include <newbinarytree.cpp>
using namespace std;
int main()
{
NewBinaryTree* newtree;
NewBinaryTree tree;
newtree = &tree;
newtree->add(10);
newtree->add(11);
newtree->add(7); **-->ALL goes well til here & debugger shows a proper tree**
newtree->printTree();**--> This method does not print the tree values properly**
return 0;
}
newbinarytree.cpp
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* left =NULL;
Node* right =NULL;
Node(int d){
data = d;
}
};
class NewBinaryTree{
private:
Node* root = NULL;
public:
NewBinaryTree(){
cout<<"Inside NewBinaryTree constructor";
}
void add(int dt){
if(root ==NULL){
Node node(dt);
root = &node;
}else{
addAsChildOf(root,dt);
}
}
void addAsChildOf(Node* tnode,int dt){
if(dt < tnode->data){
if(tnode->left == NULL){
Node newnode = Node(dt);
tnode->left = &newnode;
}else{
addAsChildOf(tnode->left,dt);
}
}else{
if(tnode->right == NULL){
Node newnode = Node(dt);
tnode->right = &newnode;
}else{
addAsChildOf(tnode->right,dt);
}
}
}
void printTree(){
if(root==NULL){
cout<<"empty tree";
}else{
printNode(this->root);
}
}
void printNode(Node* node1){ **--> This method goes into infinite loop**
if(node1==NULL){
return;
}else{
cout<<node1->data<<"[";
if(node1->left != NULL){
cout<<"Left:";
printNode(node1->left);
}
if(node1->right != NULL){
cout<<"Right:";
printNode(node1->right);
}
cout<<"]";
}
}
};
My Console output
10[Left:4210843[]Right:2686564[Left:2686564
[Left:2686564[Left:2686564[Left:2686564[Left:2686564[Left:2686564[Left:2686564[Left:.... an so on