/****************************************************************************
 *                                                                          *
 *     Loki - Programs for genetic analysis of complex traits using MCMC    *
 *                                                                          *
 *                   Simon Heath - CNG, Evry                                *
 *                                                                          *
 *                       October 2002                                       *
 *                                                                          *
 * bin_tree.c:                                                              *
 *                                                                          *
 * Routines for binary tree stuff                                           *
 *                                                                          *
 * Copyright (C) Simon C. Heath 1997, 2000, 2002                            *
 * This is free software.  You can distribute it and/or modify it           *
 * under the terms of the Modified BSD license, see the file COPYING        *
 *                                                                          *
 ****************************************************************************/

#include <stdlib.h>
#ifdef USE_DMALLOC
#include <dmalloc.h>
#endif

#include "bin_tree.h"

struct bin_node *rotate_left(struct bin_node *node)
{
	struct bin_node *l,*gc;
	
	l=node->left;
	if(l->balance==-1) {
		node->left=l->right;
		l->right=node;
		node->balance=l->balance=0;
		node=l;
	} else {
		gc=l->right;
		l->right=gc->left;
		gc->left=l;
		node->left=gc->right;
		gc->right=node;
		switch(gc->balance) {
		 case -1:
			node->balance=1;
			l->balance=0;
			break;
		 case 0:
			node->balance=l->balance=0;
			break;
		 case 1:
			node->balance=0;
			l->balance=-1;
		}
		gc->balance=0;
		node=gc;
	}
	return node;
}

struct bin_node *rotate_right(struct bin_node *node)
{
	struct bin_node *r,*gc;
	
	r=node->right;
	if(r->balance==1) {
		node->right=r->left;
		r->left=node;
		node->balance=r->balance=0;
		node=r;
	} else {
		gc=r->left;
		r->left=gc->right;
		gc->right=r;
		node->right=gc->left;
		gc->left=node;
		switch(gc->balance) {
		 case -1:
			node->balance=0;
			r->balance=1;
			break;
		 case 0:
			node->balance=r->balance=0;
			break;
		 case 1:
			node->balance=-1;
			r->balance=0;
		}
		gc->balance=0;
		node=gc;
	}
	return node;
}

void free_bin_tree(struct bin_node *node,void (*free_node)(void *))
{
	if(node->left) free_bin_tree(node->left,free_node);
	if(node->right) free_bin_tree(node->right,free_node);
	if(node->data) free_node(node->data);
	free(node);
}

