【发布时间】:2019-04-16 14:04:17
【问题描述】:
我正在从文本文件中读取命令。示例输入是:
Create Key 2
Create Key 1
Create Key 3
Update Key 1
Delete Key 2
我想减少我的程序执行的操作。比如创建Key2是没有用的,之后才删除。
为了尽量减少操作次数,我决定将这些操作存储在二叉搜索树中。在 Cormen、Leiserson、Rivest 和 Stein 所著的第三版“算法简介”一书中,二叉搜索树 (BST) 被明确定义为允许重复。键后面的字母代表创建、更新或删除。一个简单的例子如下:
K2(C)
/ \
/ \
K1(C) K3(C) <-- The deepest Key3 appears here.
\ /
K1(U) K2(D) <-- The deepest Key1 and Key2 appear here.
正如所指出的,我希望能够提取所有唯一键的最深位置,以最大限度地减少操作次数。我在 CLRS 中找不到对此的任何引用,也许我在寻找错误的东西..
返回键的简单搜索是不够的,因为它返回找到的第一个节点,因此广度优先或深度优先搜索不起作用。
struct node* search(struct node* root, int key)
{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key == key)
return root;
// Key is greater than root's key
if (root->key < key)
return search(root->right, key);
// Key is smaller than root's key
return search(root->left, key);
How to handle duplicates in Binary Search Tree? 描述了如何处理插入重复项,而不是如何处理提取最后出现的重复项。
另一个想法是返回最正确的唯一键,如下所示:
struct node * maxValueNode(struct node* node)
{
struct node* current = node;
/* loop down to find the rightmost leaf */
while (current->right != NULL)
current = current->right;
return current;
}
我在这里遗漏了什么吗?如何找到二叉树的最深 UNIQUE 节点?
【问题讨论】:
-
制作一个键映射,
。当您向树中添加某些内容时,请检查其是否在地图中。如果它在三个中的深度大于地图值,则更新。不过,不要认为你需要二叉树来解决这个问题,这将有助于更详细地解释你删除无用操作的规则。
标签: c algorithm search data-structures tree