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
| void InOrder(BSTNode *root){ if(root){ InOrder(root->lchild); std::cout << root->data << " "; InOrder(root->rchild); } }
int main(){ int arr[] = {50, 30, 70, 20, 40, 60, 80}; int n = sizeof(arr) / sizeof(arr[0]);
BSTNode *root = CreateBST(arr, n); printf("===== 初始构建的二叉搜索树(中序遍历)=====\n"); InOrder(root); printf("\n\n");
int target1 = 40; int target2 = 90;
BSTNode *res1 = RecSearch(root, target1); BSTNode *res2 = RecSearch(root, target2); printf("===== 递归查找测试 =====\n"); printf("查找 %d:%s\n", target1, res1 ? "找到" : "未找到"); printf("查找 %d:%s\n\n", target2, res2 ? "找到" : "未找到");
BSTNode *res3 = IterSearch(root, target1); BSTNode *res4 = IterSearch(root, target2); printf("===== 迭代查找测试 =====\n"); printf("查找 %d:%s\n", target1, res3 ? "找到" : "未找到"); printf("查找 %d:%s\n\n", target2, res4 ? "找到" : "未找到");
int insertVal = 55; Insert(root, insertVal); printf("===== 插入 %d 后(中序遍历)=====\n", insertVal); InOrder(root); printf("\n\n");
int del1 = 20; Delete(root, del1); printf("===== 删除叶子节点 %d 后 =====\n", del1); InOrder(root); printf("\n");
int del2 = 70; Delete(root, del2); printf("===== 删除单孩子节点 %d 后 =====\n", del2); InOrder(root); printf("\n");
int del3 = 50; Delete(root, del3); printf("===== 删除根节点 %d 后 =====\n", del3); InOrder(root); printf("\n");
return 0; }
|