BTNode* BTree_search(const BTree tree, int key, int* pos) { if (!tree) { return NULL; } int i = 0; while (i < tree->keynum && key > tree->key[i]) { ++i; } // Find the key. if (i < tree->keynum && tree->key[i] == key) { if (pos) { *pos = i; } return tree; } // tree 为叶子节点,找不到 key,查找失败返回 if (tree->isLeaf) { return NULL; } // 节点内查找失败,但 tree->key[i - 1]< key < tree->key[i], // 下一个查找的结点应为 child[i] // 从磁盘读取第 i 个孩子的数据 disk_read(&tree->child[i]); // 递归地继续查找于树 tree->child[i] return BTree_search(tree->child[i], key, pos); }
//================================================================== // 测试 B 树 //================================================================== void test_BTree_search(BTree tree, int key) { int pos = -1; BTNode* node = BTree_search(tree, key, &pos); if (node) { printf("在%s节点(包含 %d 个关键字)中找到关键字 %c,其索引为 %d\n", node->isLeaf ? "叶子" : "非叶子", node->keynum, key, pos); } else { printf("在树中找不到关键字 %c\n", key); } }