二叉查找树(二)

2014-11-24 02:32:51 · 作者: · 浏览: 4
lnode->parent->left=sonnode; else delnode->parent->right=sonnode; if(delnode!=z){ z->key=delnode->key; strcpy(z->data,delnode->data); } return delnode; } //初始化一棵树 tree init_tree(int key) { struct node * t; t=(tree)malloc(sizeof(struct node)); if(t==NULL) return NULL; t->key=key; t->parent=t->left=t->right=NULL; return t; } //释放资源 void fini_tree(tree T) { if(T!=NULL){ fini_tree(T->left); fini_tree(T->right); printf("free node(%d,%s) now\n",T->key,T->data); free(T); } } //测试程序 int main() { tree myTree=init_tree(256); if(myTree==NULL) return 1; strcpy(myTree->data,"JJDiaries"); struct record{ int key; char word[WORDLEN]; }; struct record records[]={ {2,"Viidiot"}, {4,"linux-code"}, {123,"google"}, {345,"baidu"}, {543,"nsfocus"} }; int i; struct node *tmp; for(i=0;i<5;++i){ tmp=(tree)malloc(sizeof(struct node)); if(tmp==NULL) continue; tmp->
key=records[i].key; strcpy(tmp->data,records[i].word); tmp->left=tmp->right=tmp->parent=NULL; tree_insert(&myTree,tmp); } inorder_tree_walk(myTree); struct node *del; del=tree_delete(&myTree,tree_search(myTree,345)); printf("Delete node(%d,%s)\n",del->key,del->data); free(del); inorder_tree_walk(myTree); fini_tree(myTree); } ================================================== //程序运行结果: jjdiaries@ubuntu>./search_tree key:2 words:Viidiot key:4 words:linux-code key:123 words:google key:256 words:JJDiaries key:345 words:baidu key:543 words:nsfocus Delete node(345,baidu) key:2 words:Viidiot key:4 words:linux-code key:123 words:google key:256 words:JJDiaries key:543 words:nsfocus free node(123,google) now free node(4,linux-code) now free node(2,Viidiot) now free node(543,nsfocus) now free node(256,JJDiaries) now ===================================================