AIM: To implement a simple binary search tree without peeking into
section 6.5 of K&R2 :)
PROBLEM: how can I know that the printed tree really got Left and Right
in correct order (I mean How can I be sure, how can I see that all values
larger than root went to left leg and equal or smaller ones to right leg)
/* A Binary Search Tree implementation */
#include <stdio.h>
#include <stdlib.h>
enum { TOTAL_NODES = 10,
ROOT_NODE = 0
};
struct node
{
int num;
struct node* left;
struct node* right;
};
/* To keep track of root node, root node search will always be O(1) this
way */
struct myTree
{
struct node* rootNode;
};
struct myTree* allocTree(void);
void allocRoot(struct myTree*);
struct node* addChild(struct node*, int);
void printTree(struct node*);
int main(void)
{
struct myTree* s = allocTree();
int i, j;
allocRoot(s);
for(i = j = ROOT_NODE+1; i<=TOTAL_NODES; ++i, --j)
{
addChild(s->rootNode, i);
addChild(s->rootNode, j);
}
printTree(s->rootNode);
return 0;
}
struct node* addChild(struct node* pn, int n)
{
if(NULL == pn)
{
struct node* new_node = malloc(1 * sizeof(*new_node));
if(new_node)
{
new_node->num = n;
new_node->left = new_node->right = NULL;
}
else
{
printf("Out of memory. Can't add Node(%d)\n", n);
}
pn = new_node;
}
else if(n > pn->num)
{
pn->left = addChild(pn->left, n);
}
else
{
pn->right = addChild(pn->right, n);
}
return pn;
}
void printTree(struct node* pn)
{
if(pn)
{
printf("%d\n", pn->num);
printTree(pn->left);
printTree(pn->right);
}
}
void allocRoot(struct myTree* pt)
{
struct node* rt = pt->rootNode;
rt = malloc(1 * sizeof(*rt));
if(NULL == rt)
{
printf("Out of memory, can't create root node.\n... EXITing now....
\n\n");
exit(EXIT_FAILURE);
}
rt->num = ROOT_NODE;
rt->left = rt->right = NULL;
pt->rootNode = rt;
}
struct myTree* allocTree(void)
{
struct myTree* s = malloc(1 * sizeof(*s));
if(NULL == s)
{
printf("No memory to create Tree\n..\n..\n");
exit(EXIT_FAILURE);
}
s->rootNode = NULL;
return s;
}
======================== OUTPUT ===================================
[arnuld@arch64 programs]$ gcc -ansi -pedantic -Wall -Wextra tree.c
[arnuld@arch64 programs]$ ./a.out
0
1
2
3
4
5
6
7
8
9
10
1
0
-1
-2
-3
-4
-5
-6
-7
-8
[arnuld@arch64 programs]$
--
-- arnuld
http://lispmachine.wordpress.com/