Hello All, I'm learning about BST from a book and I'm stuck half way while trying to code a BST. Here's my code:
Code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int *dataPtr;
struct node *left;
struct node *right;
}NODE;
typedef struct
{
int count;
NODE *root;
}TREE;
TREE *createTree(void)
{
TREE *tree;
tree = (TREE *)malloc(sizeof(TREE));
if(tree)
{
printf("Tree created successfully. . .\n");
tree->root = NULL;
tree->count = 0;
}
return tree;
}
void addNode(TREE *tree, int *dataInPtr)
{
NODE *newNode;
newNode = (NODE *)malloc(sizeof(NODE));
if(newNode)
{
newNode->dataPtr = dataInPtr;
newNode->left = NULL;
newNode->right = NULL;
}
if(tree->count == 0)
tree->root = newNode;
else
insertNode(tree->root, newNode, dataInPtr);
(tree->count)++;
}
NODE *insertNode(NODE *root, NODE *newNode, int *dataInPtr)
{
if(!root)
return newNode;
if(dataInPtr < root->dataPtr)
{
root->left = insertNode(root->left, newNode, dataInPtr);
return root;
}
else
{
root->right = insertNode(root->right, newNode, dataInPtr);
return root;
}
return root;
}
void inOrder(NODE *node)
{
if(node != NULL)
{
inOrder(node->left);
printf("%d\t", node->dataPtr);
inOrder(node->right);
}
}
int main(void)
{
TREE *tree;
tree = createTree();
addNode(tree->root, 20);
inOrder(tree->root);
getch();
return 0;
}
I kinda know where the problem lies. In the "else" loop of the addNode() function, I call insertNode() function which is a function with a void return type. But the insertNode() function actually return a NODE type.
I really don't know how to set the left and right nodes. I tried several things but failed. I want to do it on my own. Any help / suggestion would be appreciated.
Thanks in advance.