简体   繁体   English

C++二叉搜索树删除无序变量

[英]C++ Binary Search Tree Deletion by unordered variable

I have an ordered binary search tree by name, but im trying to delete all students who have a score less than 50. Im having difficulty because the tree is not ordered by scores, rather its ordered by name, but i need to delete by scores.我有一个按名称排序的二叉搜索树,但我试图删除所有分数低于 50 的学生。我有困难,因为树不是按分数排序,而是按名称排序,但我需要按分数删除. I cant for the life of god seem to be able to incorporate a traversal + node deletion without getting errors or it just plainly not working.我不能为上帝的生命似乎能够合并遍历 + 节点删除而不会出错,或者它显然无法正常工作。 Could someone set me in the correct direction?有人可以让我朝着正确的方向前进吗? I couldnt find any threads where they were deleting by the variable that the tree is not ordered in and couldnt find any online.我找不到任何线程,它们被树未排序的变量删除,并且无法在线找到任何线程。

Thank you.谢谢你。

This is probably best done in two passes.这可能最好分两次完成。 In the first pass, initialize an empty list of nodes.在第一遍中,初始化一个空的节点列表。 Then, do an inorder traversal of the tree and store in the list a reference to each node that needs to be deleted.然后,对树进行中序遍历,并将对每个需要删除的节点的引用存储在列表中。

In the second pass, go through the list that you created in the first pass, and delete each node, in turn.在第二遍中,遍历您在第一遍中创建的列表,依次删除每个节点。

You can also do this in a single pass by creating a new tree.您也可以通过创建新树一次性完成此操作。 Then, do an inorder traversal of the original tree, copying all of the nodes that have a score greater than or equal to 50 to the new tree.然后,对原始树进行中序遍历,将所有得分大于或等于 50 的节点复制到新树中。 When you're done, delete the old tree.完成后,删除旧树。

In general, the first method will be faster if there are few students with grades less than 50. However, if more than half of the students have scores less than 50, then the second method could very well be faster.一般来说,如果分数低于50的学生很少,第一种方法会更快。但是,如果超过一半的学生分数低于50,那么第二种方法可能会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM