二叉树的学习记录

1,创建二叉树根

2,插入二叉树节点

3,二叉树元素查找

4,二叉树删除节点

5,打印二叉树

/*
	
*/
#include <stdlib.h>
#include <stdio.h>

#define TLEN (sizeof(struct num))

typedef struct num
{
	int n;
	struct num *Ltree;
	struct num *Rtree;
}*NumTree;

/*
	创建二叉树 
*/ 
NumTree createNewTree(int n)
{
	NumTree T=(NumTree)malloc(sizeof(struct num));
	if(T==NULL)
	{
		printf("内存申请失败\n");
		return NULL; 
	}
	T->n=n;
	T->Ltree=NULL;
	T->Rtree=NULL;
	return T;
}

/*
	插入节点 
*/ 
NumTree insertElement(NumTree T,int n)
{
	if(T==NULL)
	{
		T=(NumTree)malloc(sizeof(struct num));	
		if(T==NULL)
		{
			printf("申请内存失败\n");
		}
		else
		{
			T->n=n; 
			T->Ltree=T->Rtree=NULL;
		}
	}
	else if(n<T->n)
	{
		T->Ltree=insertElement(T->Ltree,n);
	}
	else if(n>T->n)
	{
		T->Rtree=insertElement(T->Rtree,n);
	}
	return T;
}

/*
	寻找节点 
*/
NumTree findElement(NumTree T,int n)
{
	if(n<T->n)
	{
		return findElement(T->Ltree,n);		
	}
	else if(n>T->n)
	{
		return findElement(T->Rtree,n);
	}
	else
	{
		return T;
	}
}

/*
	找到最小项 
*/
NumTree findMin(NumTree T)
{
	NumTree p=T->Ltree;
	while(p!=NULL)
	{
		p=p->Ltree;
	}	
	return p;
}
/*
	删除节点 
*/
NumTree deleteElement(NumTree T,int n)
{
	NumTree t;
	if(n<T->n)
	{
		T->Ltree=deleteElement(T->Ltree,n);
	} 
	else if(n>T->n)
	{
		T->Rtree=deleteElement(T->Rtree,n);
	}
	else if((T->Ltree!=NULL)&&(T->Rtree)!=NULL)
	{
		t=findMin(T->Rtree);
		T->n=t->n;
		T->Rtree=deleteElement(T->Ltree,T->n);
	}
	else
	{
		t=T;
		if(T->Ltree==NULL)
		{
			T=T->Rtree;	
		}
		else if(T->Rtree==NULL)
		{
			T=T->Ltree;		
		}
		free(t);
	}
	return T;
}

/*
	打印树 
*/
void printfTree(NumTree T)
{
	if(T!=NULL)
	{
		printf("%d\n",T->n);
		printfTree(T->Ltree);
		printfTree(T->Rtree);
	}	
}

int main()
{
	NumTree T0;
	T0=createNewTree(100);
	insertElement(T0,80);	
	insertElement(T0,120);	
	insertElement(T0,90);	
	insertElement(T0,110);
	printfTree(T0);
	deleteElement(T0,80);
	printfTree(T0);
}

  

posted on 2017-01-25 14:20  HelloWorldTotti  阅读(168)  评论(0编辑  收藏  举报

导航