typedefstructTreeNode *Tree; typedefstructTreeNodeTreeNode; structTreeNode { int element; Tree left; Tree right; };
// Find 查找指向树T中具有关键字X的结点的指针,如果这样的结点不存在则返回NULL Tree Find(int x, Tree t) { if (t == NULL) { returnNULL; } if (x < t->element) { return Find(x, t->left); } elseif (x > t->element) { return Find(x, t->right); } return t; }
// FindMin 返回最小元的结点的指针 Tree FindMin(Tree t) { if (t == NULL) { returnNULL; } if (t->left == NULL) { returnNULL; } return FindMin(t->left); }
// FindMax 返回最大元的结点的指针 Tree FindMax(Tree t) { if (t == NULL) { returnNULL; } Tree cur = t; while (cur->right != NULL) { cur = cur->right; } return cur; }
// Insert 插入元素x Tree Insert(int x, Tree t) { if (t == NULL) { Tree t = (Tree)malloc(sizeof(TreeNode)); if (t == NULL) { printf("out of space!!!\n"); returnNULL; } t->element = x; t->left = NULL; t->right = NULL; return t; } if (x < t->element) { t->left = Insert(x, t->left); } if (x > t->element) { t->right = Insert(x, t->right); } return t; }
// Delete 删除指定结点 Tree Delete(int x, Tree t) { Tree tmpCell; if (t == NULL) { returnNULL; } if (x == t->element) { // 该结点有两个子结点 // 一般的删除策略是用其右子树的最小的数据代替该结点的数据并递归的删除那个结点 if (t->left != NULL && t->right != NULL) { tmpCell = FindMin(t->right); t->element = tmpCell->element; t->right = Delete(t->element, t->right); } else { tmpCell = t; if (t->left == NULL) { t = t->right; } elseif (t->right==NULL) { t = t->left; } free(tmpCell); } } if (x > t->element) { t->right = Delete(x, t->right); } if (x < t->element) { t->left = Delete(x, t->left); } return t; }