数据结构之 排序二叉树总结

2/10/2017来源:ASP.NET技巧人气:291

1.查找数,2.查找最小数(递归方法),3.查找最大数(迭代方法) 4.知道如何插入一个数,就知道如何创建一个排序二叉树废话不多说上函数代码 x是要插入的数,root是对应待插入的树,5.如何删除一个数。

ST *find(int x, ST *root)/*查找x这个数*/ { while(root) { if(x > root->data) root = root->rt; else if(x < root->data) root = root->lt; else return root; } return 0; } ST *minfind(ST *root)/*递归方法*/ { if(!root) return NULL; else if(!root->lt) return root; else midfind(root->lt); } ST *maxfind(ST *root)/*迭代的方法*/ { if(root) { while(root->rt) { root = root->rt; } } return root; } ST *insert(int x, ST *root) { if(root == NULL) { root = (ST *)malloc(sizeof(ST)); root->data = x; root->lt = NULL; root->rt = NULL; } else { if(x > root->data) root->rt = insert(x, root->rt); else root->lt = insert(x, root->lt); } return root; } ST *delete(int x, ST *root) { ST *p; if(root) { if(x > root->data) { root->rt = delete(x, root->rt); } else if(x < root->data) { root->lt = delete(x, root->lt); } else { if(root->lt && root->rt) { p = minfind(root-rt); root->data = p->data; root->rt = delete(root->data, root->rt); } else { p = root; if(!root->lt) root = root->rt; else if(!root->rt) root = root->lt; free(p); } } } }