生成二叉树和红黑树的helloworld(2)

[code="java"]
# cat ctree.h
typedef struct node *link;
struct node{
int item;link l,r;
};
void print_tree(struct node * root);
[/code]



#include <math.h>
#include <curses.h>
#include "ctree.h"
static void recur_print( struct node * node, int line, int col ){
if( node == NULL ){
move( line, col ) ;
addstr("*");//此处为加*号的代码,用来占位,可去掉。
return ;
}
int t = COLS/pow( 2, line+2 );
char buf[9];
sprintf(buf,"%-d", node->item ) ;
move( line , col ) ;
addstr( buf ) ;
if( node->l != NULL || node->r != NULL ){
move(line+1, col-t-1 ) ;
addstr("[");
move(line+1, col+t+3) ;
addstr("]");
}
recur_print( node->l, line+1, col-t ) ;
recur_print( node->r, line+1, col+t ) ;
}
void print_tree(struct node * root){
initscr() ;
clear();
recur_print(root, 0, COLS/2);
move(LINES-1, COLS-1) ;
refresh() ;
getchar() ;
endwin() ;
}



[code="java"]
# cat bst.c
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "ctree.h"
#define N 10
link NODE(int item,link l,link r){
link t=malloc(sizeof *t);
t->item=item;t->l=l;t->r=r;
return t;
}
link insert_node(link t,int item){
if(t==NULL) return NODE(item,NULL,NULL);
if(item<t->item)
t->l=insert_node(t->l,item);
else
t->r=insert_node(t->r,item);
return t;
}
void pprint(link t){
printf("(");
if(t!=NULL){
printf("%d",t->item);
pprint(t->l);
pprint(t->r);
}
printf(")");
}
int bst_search(link t,int item){
if(t==NULL) return 0;
if(item<t->item)return bst_search(t->l,item);
else if(item>t->item) return bst_search(t->r,item);
else return 1;
}
link bst_remove(link t,int item){
if(t==NULL) return NULL;
if(item<t->item)
t->l=bst_remove(t->l,item);
else if(item>t->item){
t->r=bst_remove(t->r,item);
}else {
link x;
if(t->l){
for(x=t->l;x->r;x=x->r){;}
t->item=x->item;
t->l=bst_remove(t->l,t->item);
}else if(t->r){
for(x=t->r;x->l;x=x->l){;}
t->item=x->item;
t->r=bst_remove(t->l,t->item);
}else{
free(t);t=NULL;
}
}
return t;
}
int main(){
srand(time(NULL));
int i ;link root=NULL;
for(i=0;i<N;i++) root =insert_node(root,rand()%100);
printf("\t\\tree");pprint(root);
print_tree(root);
return 0;
}
[/code]

执行:

gcc -lcurses -lm bst.c ctree.c

[img]http://dl.iteye.com/upload/attachment/0083/3649/66c86847-5af2-3038-a083-9b9fe40124ba.jpg[/img]

跟那个还是有点差距
不过也差不多了哈哈哈
[img]http://dl.iteye.com/upload/attachment/0083/3651/9c1fbc87-79de-3b27-8e2d-a6bce96bf088.jpg[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值