二叉树(1)

完成二叉树部分内容了。

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */


typedef struct _data{
	int id;
	char name[20];
}data;

typedef struct _bnode{
	data *d;
	struct _bnode *parent,*left,*right;
}bnode;

typedef struct _btree{
	bnode *root;
}btree;

bnode *btree_find_node(bnode *t,int id){	
	if(NULL!=t){
		if(t->d->id==id){
			return t;
		}
		
		bnode *p=btree_find_node(t->left,id);
		if(NULL==p){
			p=btree_find_node(t->right,id);
		}
		
		return p;

	}
	
	return NULL;
	
}



void btree_iterate(bnode *t){
	
	if(t!=NULL){
		printf("id=%d\n",t->d->id);
		if(t->left!=NULL){
			btree_iterate(t->left);
		}
		
		if(t->right!=NULL){
			btree_iterate(t->right);
		}
	}
	
}









int btree_append_child(btree *l,int pid,data *d){
	bnode *p=btree_find_node(l->root,pid);
	if(NULL!=l->root && NULL==p){
		printf("Append child error!");
		return 0;
	}
	
	if((l->root!=NULL) && (p->left!=NULL&&p->right!=NULL)){
		printf("The previous node is full!");
		return 0;
	}
	
	bnode *t=(bnode *)malloc(sizeof(bnode));
	if(t==NULL){
		printf("Memoruy overflow!");
		return 0;
	}
	t->d=d;
	t->left=NULL;
	t->parent=NULL;
	t->right=NULL;
	
	if(l->root==NULL){
		l->root=t;
		printf("l->root->id=%d\n",t->d->id);
		return -1;
	}
	
	if(p->left==NULL){
		p->left=t;
		t->parent=p;
		printf("id=%d->left->d->id=%d\n",p->d->id,p->left->d->id);
	}else{
		p->right=t;
		t->parent=p;
		printf("id=%d->right->d->id=%d\n",p->d->id,p->right->d->id);
	}
	
	return -1;
	
}











int main() {
	data *d;
	btree *t=(btree *)malloc(sizeof(btree));
	if(t==NULL){
		printf("Memory overflow!");
		return 0;
	}
	t->root=NULL;
	
	d=(data *)malloc(sizeof(data));
	if(d==NULL){
		printf("Memory overflow!");
		return 0;
	}
	d->id=1;
	strcpy(d->name,"a");
	btree_append_child(t,-1,d);	
	
	d=(data *)malloc(sizeof(data));
	if(d==NULL){
		printf("Memory overflow!");
		return 0;
	}
	d->id=2;
	strcpy(d->name,"b");
	btree_append_child(t,1,d);	
	 
	d=(data *)malloc(sizeof(data));
	if(d==NULL){
		printf("Memory overflow!");
		return 0;
	}
	d->id=3;
	strcpy(d->name,"c");
	btree_append_child(t,1,d);	

	d=(data *)malloc(sizeof(data));
	if(d==NULL){
		printf("Memory overflow!");
		return 0;
	}
	d->id=4;
	strcpy(d->name,"d");
	btree_append_child(t,2,d);	
	
	d=(data *)malloc(sizeof(data));
	if(d==NULL){
		printf("Memory overflow!");
		return 0;
	}
	d->id=5;
	strcpy(d->name,"e");
	btree_append_child(t,2,d);	
	
	d=(data *)malloc(sizeof(data));
	if(d==NULL){
		printf("Memory overflow!");
		return 0;
	}
	d->id=6;
	strcpy(d->name,"f");
	btree_append_child(t,3,d);	

	btree_iterate(t->root);
	
	getch();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值