二叉搜身树(BST)的插入、删除、查找、遍历
#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); } }
分别列了三种遍历方法:前序,中序(一般用于按顺序显示二叉搜索树的节点),后序。