What's the case for duplications in BST?

被刻印的时光 ゝ 提交于 2019-12-25 16:40:24

问题


How to solve the problem with duplication in Binary Search Tree?


回答1:


I am not really sure what you are asking. But that won't stop me from posting an answer.

Usually, duplicate keys are disallowed in a BST. That tends to make things a lot easier, and it is a condition that is easy to avoid.

If you do want to allow duplicates, then insertions are not a problem. You can just stick it either in the left subtree or the right subtree.

The problem is that you can't count on the duplicates being on a particular side if it is a self-balancing tree like an AVL-tree or a red-black-tree. It seems like this might be a problem for deletions, but I once implemented an AVL-tree that made no special provisions for duplicates, and it had no problems at all.

Deleting a node from an AVL tree involves (1) finding the node, (2) replacing that node with either the greatest key in the left subtree or the smallest key in the right subtree, and then recursively deleting that node. If there is no subtree, then nothing more needs to be done.

In practice, deleting a node with duplicates means that the node with the sought key nearest the root will be replaced with something, either a node with another key, or a node with the same key. Either way, the ordering constraints are not violated, and everything proceeds with no trouble.

I don't know about red-black trees or other sorts of BSTs.




回答2:


It's up to your comparison check: if equal and smaller are equivalent, duplicates will be placed in the "smaller" node, otherwise they're in the "larger" node. Besides this, there shouldn't be an issue with duplicates, unless you want to avoid them of course, in which case you need an extra equality check.



来源:https://stackoverflow.com/questions/2548711/whats-the-case-for-duplications-in-bst

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!