头文件:
#include<iostream> using namespace std; typedef struct BiTNode { int data; int key; struct BiTNode *parent, *lchild, *rchild; }BiTNode, *BiTree; BiTree Tree_Search(BiTree x, int k); void Tree_Walk(BiTree x); BiTree Tree_Minimun(BiTree x); BiTree Tree_Maximun(BiTree x); void Tree_Insert(BiTree &T, BiTree z); void Tree_Delete(BiTree &T, BiTree z); void Transplant(BiTree &T, BiTree u, BiTree v);
实现部分:
#include "searchTree.h" BiTree Tree_Search(BiTree x, int k) //查找二叉搜索树。Tree-Search返回一个指向关键字为key的节点的指针;否则返回NULL { if ((x == NULL) || (k == x->key)) { return x; } if (k < x->key) { return Tree_Search(x->lchild, k); } else { return Tree_Search(x->rchild, k); } } void Tree_Walk(BiTree x) //遍历 { if (x != NULL) { Tree_Walk(x->lchild); cout << x->key << endl; Tree_Walk(x->rchild); } } BiTree Tree_Minimun(BiTree x) { while (x->lchild != NULL) { x = x->lchild; } return x; } BiTree Tree_Maximun(BiTree x) { while (x->rchild != NULL) { x = x->rchild; } return x; } void Tree_Insert(BiTree &T,BiTree z) { BiTree y = NULL; BiTree x = T; while (x != NULL) { y = x; if (z->key < x->key) { x = x->lchild; } else { x = x->rchild; } } z->parent = y; if (y == NULL) { T = z; } else if (z->key < y->key) { y->lchild = z; } else { y->rchild = z; } } void Transplant(BiTree &T, BiTree u, BiTree v) { if (u->parent == NULL) { T = v; } else if (u == u->parent->lchild) { u->parent->lchild = v; } else { u->parent->rchild = v; } if (v != NULL) { v->parent = u->parent; } } void Tree_Delete(BiTree &T, BiTree z) { if (z->lchild == NULL) { Transplant(T, z, z->rchild); } else if (z->rchild == NULL) { Transplant(T, z, z->lchild); } else { BiTree y = Tree_Minimun(z->rchild); if (y->parent != z) { Transplant(T, y, y->rchild); y->rchild = z->rchild; y->rchild->parent = y; } Transplant(T, z, y); y->lchild = z->lchild; y->lchild->parent = y; } } int main() { BiTree oldTree = NULL; for (int i = 0; i < 10; ++i) { BiTree testNode = new BiTNode(); testNode->key = rand()%100; Tree_Insert(oldTree, testNode); } Tree_Walk(oldTree); cout << "The Max is " << Tree_Maximun(oldTree)->key << endl; cout << "The Max is " << Tree_Minimun(oldTree)->key << endl; Tree_Delete(oldTree, Tree_Maximun(oldTree)); Tree_Delete(oldTree, Tree_Minimun(oldTree)); Tree_Walk(oldTree); return 0; }
时间: 2024-10-15 11:13:10