15 September 2009

binary tree in C

int count(node *head)
{
if(head == NULL) return 0;

return count(head->left) + 1 + count(head->right);
}

int depth(node *head)
{
if(head == NULL)
return 0;
else
{
int ldepth = depth(head->left);
int rdepth = depth(head->right);

if(ldepth < rdepth) return rdepth+1;
else return ldepth+1;
}
}

int compare(node *n1, node *n2)
{
if(n1==NULL && n2==NULL)
return true;
else if(n1!=NULL && n2!=NULL)
{
return ((n1->val==n2->val) &&
compare(n1->left, n2->left) &&
compare(n1->right, n2->right));
}
else return false;
}

-----------------btree.c-----------------
#include <stdio.h>
#include <stdlib.h>

typedef struct node{
int val;
struct node *left;
struct node *right;
}node;


void print(node *head)
{
if(head == NULL) return;

print(head->left);
printf("%d->",head->val);
print(head->right);
}

node * insert(node *head, int val)
{
if(head == NULL)
{
head = (node*)malloc(sizeof(node));
head->left=head->right=NULL;
head->val = val;
}
else if(val < head->val)
head->left = insert(head->left, val);
else if(val > head->val)
head->right = insert(head->right, val);
else
printf("duplicate vale (%d)\n", val);

return head;
}

int count(node *head)
{
if(head == NULL) return 0;

return count(head->left) + 1 + count(head->right);
}

int count2(node *head)
{
int count = 0;

if(head == NULL) return 0;
count += count2(head->left);
count += count2(head->right);

return ++count;
}

void count3(node *head, int *count)
{
if(head == NULL) return;

count3(head->left, count);
count3(head->right, count);
(*count)++;
}

int depth(node *head)
{
if(head == NULL)
return 0;
else
{
int ldepth = depth(head->left);
int rdepth = depth(head->right);

if(ldepth < rdepth) return rdepth+1;
else return ldepth+1;
}
}

#define true 1
#define false 0
int compare(node *n1, node *n2)
{
if(n1==NULL && n2==NULL)
return true;
else if(n1!=NULL && n2!=NULL)
{
return ((n1->val==n2->val) &&
compare(n1->left, n2->left) &&
compare(n1->right, n2->right));
}
else return false;
}

int main()
{
node *head1 = NULL;
node *head2 = NULL;
int c1 = 0;

head1 = insert(head1, 50);
insert(head1, 40);
insert(head1, 70);
insert(head1, 30);
insert(head1, 25);
insert(head1, 90);
insert(head1, 45);
insert(head1, 10);
insert(head1, 55);
insert(head1, 85);
print(head1); printf("NULL\n");

head2 = insert(head2, 50);
insert(head2, 40);
insert(head2, 70);
insert(head2, 30);
insert(head2, 25);
insert(head2, 90);
insert(head2, 45);
insert(head2, 10);
insert(head2, 55);
insert(head2, 85);
print(head2); printf("NULL\n");

printf("number of nodes in the tree is %d\n", count(head1));
printf("Max depth of the tree is %d\n", depth(head1));
printf("comparison for both the tree is \"%s\"\n",
compare(head1, head2)?"true":"false");

return 0;
}
-----------------------------------------

Reference:
http://cslibrary.stanford.edu/110/BinaryTrees.html

No comments:

Post a Comment