I am learning c++ and data structures I have implemented binary search tress can any body tell what is the issue in this code I am getting root pointer as null. Basically unable to create a tree. My final goal is to search the key in the tree. i have written a method for it. but unfortunately i am unable to create a tree. I have tested it by writing the traversal code.
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
// Node structure
struct TreeNode {
int value;
int key;
struct TreeNode *left;
struct TreeNode *right;
TreeNode()
{
left=NULL;
right=NULL;
}
};
void preOrder (TreeNode *);
void insertNode(TreeNode *, int, int);
TreeNode* findNode(TreeNode *aNode, int);
void main() {
TreeNode *root = NULL;
for(int i = 15; i<= 300; i+=15) {
insertNode(root, i, i);
if (root!=NULL) {
cout<<root ->value<<endl;
}
}
cout<<"The preorder traversal"<<endl;
preOrder(root);
getch();
}
void preOrder (TreeNode *p) {
if (p!=NULL) {
cout<<p ->value<<endl;
preOrder(p ->left);
preOrder(p ->right);
} else{
cout << "NULL"<<endl;
}
}
void createNewNode(TreeNode *newNode, int aValue, int aKey) {
newNode = new TreeNode; // create new node
newNode -> value = aValue; // set data
newNode -> key = aKey; // set key
cout<<newNode ->value<<endl;
// Set left,right
newNode -> left = newNode -> right = NULL;
}
void insertNode(TreeNode *aNode, int aValue, int aKey) {
if (aNode == NULL) {
TreeNode *newNode = new TreeNode; // create new node
newNode -> value = aValue; // set data
newNode -> key = aKey; // set key
//createNewNode(newNode, aValue, aKey);
if(newNode == NULL) {
cout<< "Null returned"<<endl;
} else {
cout<< newNode -> key <<endl;
}
aNode = newNode;
} else if (aKey == aNode->key) {
cout<<aKey<<endl;
return;
} else if (aKey < aNode->key) {
insertNode((aNode->left), aValue, aKey);
} else {
insertNode((aNode->right), aValue, aKey);
}
}
TreeNode* findNode(TreeNode *aNode, int aKey) {
if (aNode == NULL) {
return NULL;
} else if (aNode->key == aKey) {
return aNode;
} else if (aKey <= aNode->key) {
return findNode(aNode->left, aKey);
} else {
return findNode(aNode->right, aKey);
}
}