阅读更多
[root@VM_253_237_tlinux ~/tree/print]# cat ctree.h
typedef struct node *link;
struct node{
int item;link l,r;
};
void print_tree(struct node * root);
#include
#include
#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() ;
}
[root@VM_253_237_tlinux ~/tree/print]# cat bst.c
#include
#include
#include
#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(itemitem)
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(itemitem)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(itemitem)
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
执行:
gcc -lcurses -lm bst.c ctree.c
跟那个还是有点差距
不过也差不多了哈哈哈
- 大小: 7.1 KB
- 大小: 70.9 KB