简体   繁体   中英

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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