cmq in C potrebbe essere na cosa simile:
codice:
/*
### Copyright (c) 2004 Luca Francesca
### This script is provided under the terms of the GNU General Public License
### (see http://www.gnu.org/licenses/gpl.html for the full license text.)
*/
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "Common.h"
#define YES 0
#define NO !YES
typedef struct _TreeNode *Node;
struct _TreeNode
{
int data;
Node l, r;
};
Node Init(int val);
Node Add(int val, Node aux);
void Delete(Node aux);
void ShowInOrder(Node aux);
uint IsRight(Node aux);
int main(int argc, char *argv[])
{
srand(time(NULL));
Node root = Init(1);
int i = 0, ival = 0;
for(i; i < 10;++i)
{
ival = i + (rand()%10);
root = Add(ival, root);
}
if(IsRight(root) == YES)
{
puts("The tree is righted\n");
}
ShowInOrder(root);
Delete(root);
SAFE_DELETE(root)
ExitFunction();
return 0;
}
Node Init(int val)
{
Node tmp;
tmp = malloc(sizeof(struct _TreeNode));
tmp->data = val;
tmp->l = tmp->r = NULL;
return tmp;
}
Node Add(int val, Node aux)
{
if(aux == NULL)
{
aux = malloc(sizeof(struct _TreeNode));
aux->data = val;
aux->l = aux->r = NULL;
}
else if(val > aux->data)
aux->l = Add(val, aux->l);
else if(val <= aux->data)
aux->r = Add(val, aux->r);
return aux;
}
void ShowInOrder(Node aux)
{
if (aux->l) ShowInOrder(aux->l);
fprintf(stdout, "%d \n", aux->data);
if (aux->r) ShowInOrder(aux->r);
}
uint IsRight(Node aux)
{
uint nl, nr = 0;
while(aux != NULL)
{
if(aux->l) nl++;
if(aux->r) nr++;
}
return (nr > nl) ? YES : NO;
}
void Delete(Node aux)
{
while(aux != NULL)
{
free(aux->l);
free(aux->r);
free(aux);
}
aux = NULL;
}