1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| #include <stdio.h> #include <stdlib.h>
typedef int KeyType; typedef struct BSTNode { KeyType key; struct BSTNode *lchild, *rchild; } BSTNode, *BiTree;
int insertBST(BiTree &T, KeyType k) { BiTree treeNew = (BiTree) calloc(1, sizeof(BSTNode)); treeNew->key = k; if (NULL == T) { T = treeNew; return 1; } BiTree p = T, parent; while (p) { parent = p; if (k > p->key) { p = p->rchild; } else if (k < p->key) { p = p->lchild; } else { return -1; } } if (k > parent->key) { parent->rchild = treeNew; } else { parent->lchild = treeNew; } return 0; }
void createBST(BiTree &T, KeyType *str, int len) { int i; for (i = 0; i < len; i++) { insertBST(T, str[i]); } }
void createBSTOrder(BiTree &T, KeyType *str, int len) { T = NULL; int i; while (i < len) { insertBST(T, str[i]); i++; } }
void inOrder(BiTree T) { if (T != NULL) { inOrder(T->lchild); printf("%3d", T->key); inOrder(T->rchild); } }
BiTree searchBST(BiTree T, KeyType k, BiTree parent) { parent = NULL; while (T != NULL && k != T->key) { parent = T; if (k < T->key) { T = T->lchild; } else { T = T->rchild; } } return T; }
void deleteNode(BiTree &root, KeyType x) { if (root == NULL) { return; } if (root->key > x) { deleteNode(root->lchild, x); } else if (root->key < x) { deleteNode(root->rchild, x); } else { if (root->lchild == NULL) { BiTree tempNode = root; root = root->rchild; free(tempNode); } else if (root->rchild == NULL) { BiTree tempNode = root; root = root->lchild; free(tempNode); } else { BiTree tempNode = root->lchild; while (tempNode->rchild != NULL) { tempNode = tempNode->rchild; } root->key = tempNode->key; deleteNode(root->lchild, tempNode->key); } } }
int main() { BiTree T = NULL; BiTree parent; BiTree search; KeyType str[7] = {54, 20, 66, 40, 28, 79, 58}; createBST(T, str, 7); inOrder(T); printf("\n"); search = searchBST(T, 40, parent); if (search) { printf("找到相应的节点=%d\n", search->key); } else { printf("没有找到"); } createBSTOrder(T, str, 7); printf("排序后的二叉树\n"); inOrder(T); printf("\n"); deleteNode(T, 40); inOrder(T); return 0; }
|