二叉搜身树(BST)的插入、删除、查找、遍历
2013-09-25 16:53
465 查看
#include <stdio.h> #include <stdlib.h> typedef struct node { int id; struct node *left; struct node *right; } node; node *find(int id, node *root) { if (root == NULL) return (NULL); if (id < root->id) return (find(id, root->left)); else if (id > root->id) return (find(id, root->right)); else return root; } node *findmin(node *root) { if (root == NULL) return (NULL); if (root->left == NULL) return (root); else return (findmin(root->left)); } node *insert(int id, node *root) { if (root == NULL) { root = malloc(sizeof(node)); if (root == NULL) { printf("out of memory\n"); return (NULL); } root->id = id; root->left = root->right = NULL; } else if (id < root->id) { root->left = insert(id, root->left); } else if(id > root->id) { root->right = insert(id, root->right); } return (root); } node *delete(int id, node *root) { node *tmp; if (root == NULL) printf("not found"); else if (id < root->id) root->left = delete(id, root->left); else if (id > root->id) root->right = delete(id, root->right); else { if (root->left && root->right) { tmp = findmin(root->right); root->id = tmp->id; root->right = delete(root->id, root->right); } else /* one or zero children */ { tmp = root; if (root->left == NULL) root = root->right; else if (root->right == NULL) root = root->left; free(tmp); } } return root; } oid retrieve(node *root) // preorder { if (root) { printf("%d ", root->id); retrieve(root->left); retrieve(root->right); } } void inorder(node *root) // inorder { if (root) { inorder(root->left); printf("%d ", root->id); inorder(root->right); } } void postorder(node *root) // postorder { if (root) { postorder(root->left); postorder(root->right); printf("%d ", root->id); } }
分别列了三种遍历方法:前序,中序(一般用于按顺序显示二叉搜索树的节点),后序。
相关文章推荐
- BST 插入删除查找遍历
- 二叉树的查找,插入,删除,遍历,最小值,最大值 操作
- Javascript数据结构算法之二叉查找树BST(构造,遍历,查找,删除,计数)
- 二叉查找数 插入 删除
- 二叉排序树的建立、插入、删除、查找、比较、4种遍历方式的C++完整实现版
- 单链表建立,插入,删除,查找,遍历操作
- 二叉查找数 插入 删除
- 二叉查找树(插入、查找、遍历、删除.........)
- 二叉排序树的构造,插入,遍历,查找,删除
- 二叉排序数(创建,插入,删除,查找及前序、中序、后序遍历)
- BST的查找、插入、删除
- 二叉搜索树Java实现(查找、插入、删除、遍历)
- 二叉搜索树(BST)递归与非递归的插入、删除、查找的实现
- 二叉排序树的插入、查找、删除、遍历(C语言版)
- java 模拟数组(Array)的查找、插入、删除、遍历
- 算法学习----二叉树的查找、 删除、插入、遍历
- 单链表建立,插入,删除,查找,遍历操作!!!!
- C++ 二叉树(创建,遍历,查找,插入,删除)『菜鸟版』
- 顺序表的建立、插入、删除、查找、遍历操作
- C++ STL list的初始化、添加、遍历、插入、删除、查找、排序、释放