二叉搜索树模板
二叉搜索树
特征:左子树的key值小于根节点,右子树的key值大于根节点。
模板程序
1 //二叉搜索树 2 struct Node { 3 int key; 4 Node* parent; 5 Node* leftChild; 6 Node* rightChild; 7 Node() { 8 key = 0; 9 parent = leftChild = rightChild; 10 } 11 }; 12 13 struct BinarySearchTree { 14 Node* root; 15 Node* search(Node* node, int key) {//基于性质,左子树较小,右子树较大 16 while (node != nil && node->key != key){ 17 if (node->key > key) node = node->leftChild; 18 else node = node->rightChild; 19 } 20 return node; 21 } 22 Node* minimum(Node* node) { 23 while (node->leftChild != nil){ 24 node = node->leftChild; 25 } 26 return node; 27 } 28 Node* maximum(Node* node) { 29 while (node->rightChild != nil){ 30 node = node->rightChild; 31 } 32 return node; 33 } 34 Node* predecessor(Node* node) { 35 if (node->leftChild != nil){//左子树的最大值 36 return maximum(node->leftChild); 37 } 38 //如果没有左子树,则前驱是第一个比目标小的先辈结点 39 while (node->parent != nil && node == node->parent->leftChild){ 40 node = node->parent; 41 } 42 return node->parent; 43 } 44 Node* successor(Node* node) { 45 if (node->rightChild != nil){ 46 return minimum(node->rightChild); 47 } 48 while (node->parent != nil && node == node->parent->rightChild){ 49 node = node->parent; 50 } 51 return node->parent; 52 } 53 54 55 56 void insert(Node* node) { 57 Node *father = root; 58 while (true){ 59 if (father->key > node->key){ 60 if (father->leftChild == nil)break; 61 father = father->leftChild; 62 }else{ 63 if (father->rightChild == nil)break; 64 father = father->rightChild; 65 } 66 } 67 if (father == root){ 68 root = node; 69 }else if (father->key > node->key){ 70 father->leftChild = node; 71 node->parent = father; 72 }else{ 73 father->rightChild = node; 74 node->parent = father; 75 } 76 } 77 void replace(Node* des, Node* src) { 78 if (des->parent == nil){ 79 root = src; 80 }else if (des == des->parent->leftChild){ 81 des->parent->leftChild = src; 82 }else{ 83 des->parent->rightChild = src; 84 } 85 if (src != nil){ 86 src->parent = des->parent; 87 } 88 } 89 void del(Node* node) { 90 if (node->leftChild == nil){ 91 replace(node, node->rightChild); 92 }else if (node->rightChild == nil){ 93 replace(node, node->leftChild); 94 }else{ 95 Node *suc = minimum(node->rightChild); 96 node->key = suc->key; 97 replace(suc, suc->rightChild); 98 } 99 } 100 }; 101 Node* suc = minimum(node->rightChild); 102 if (suc->parent != node) { 103 replace(suc, suc->rightChild); 104 suc->rightChild = node->rightChild; 105 suc->rightChild->parent = suc; 106 } 107 replace (node, suc); 108 suc->leftChild = node->leftChild; 109 suc->leftChild->parent = suc;