Are duplicate keys allowed in the definition of binary search trees?

后端 未结 12 737
慢半拍i
慢半拍i 2020-11-29 15:40

I\'m trying to find the definition of a binary search tree and I keep finding different definitions everywhere.

Some say that for any given subtree the left child k

相关标签:
12条回答
  • 2020-11-29 16:06

    In a BST, all values descending on the left side of a node are less than (or equal to, see later) the node itself. Similarly, all values descending on the right side of a node are greater than (or equal to) the nodes value(a).

    Some BSTs may choose to allow duplicate values, hence the "or equal to" qualifiers above. The following example may clarify:

         14
        /  \
      13    22
     /     /  \
    1    16    29
              /  \
            28    29
    

    This shows a BST that allows duplicates(b) - you can see that to find a value, you start at the root node and go down the left or right subtree depending on whether your search value is less than or greater than the node value.

    This can be done recursively with something like:

    def hasVal (node, srchval):
        if node == NULL:
             return false
        if node.val == srchval:
            return true
        if node.val > srchval:
            return hasVal (node.left, srchval)
        return hasVal (node.right, srchval)
    

    and calling it with:

    foundIt = hasVal (rootNode, valToLookFor)
    

    Duplicates add a little complexity since you may need to keep searching once you've found your value, for other nodes of the same value.


    (a) You could actually sort them in the opposite direction should you so wish provided you adjust how you search for a specific key. A BST need only maintain some sorted order, whether that's ascending or descending is not relevant.


    (b) Interestingly, if your sorting key uses the entire value stored at a node (so that nodes containing the same key have no other extra information to distinguish them), there can be performance gains from adding a count to each node, rather than allowing duplicate nodes.

    The main benefit is that adding or removing a duplicate will simply modify the count rather than inserting or deleting a new node, an action that may require re-balancing the tree.

    So, to add an item, you first check if it already exists. If so, just increment the count and exit. If not, you need to insert a new node with a count of one then rebalance.

    To remove an item, you find it then decrement the count - only if the resultant count is zero do you then remove the actual node from the tree and rebalance.

    Searches are also quicker given there are fewer nodes but that may not be a large impact.

    For example, the following two trees (non-counting on the left, and counting on the right) would be equivalent (in the counting tree, i.c means c copies of item i):

         __14__                    ___22.2___
        /      \                  /          \
      14        22             7.1            29.1
     /  \      /  \           /   \          /    \
    1    14  22    29      1.1     14.3  28.1      30.1
     \            /  \
      7         28    30
    

    Removing the leaf-node 22 from the left tree would involve rebalancing (since it now has a height differential of two) the resulting 22-29-28-30 subtree such as below (this is one option, there are others that also satisfy the "height differential must be zero or one" rule):

    \                      \
     22                     29
       \                   /  \
        29      -->      28    30
       /  \             /
     28    30         22
    

    Doing the same operation on the right tree is a simple modification of the root node from 22.2 to 22.1 (with no rebalancing required).

    0 讨论(0)
  • 2020-11-29 16:06

    In the book "Introduction to algorithms", third edition, by Cormen, Leiserson, Rivest and Stein, a binary search tree (BST) is explicitly defined as allowing duplicates. This can be seen in figure 12.1 and the following (page 287):

    "The keys in a binary search tree are always stored in such a way as to satisfy the binary-search-tree property: Let x be a node in a binary search tree. If y is a node in the left subtree of x, then y:key <= x:key. If y is a node in the right subtree of x, then y:key >= x:key."

    In addition, a red-black tree is then defined on page 308 as:

    "A red-black tree is a binary search tree with one extra bit of storage per node: its color"

    Therefore, red-black trees defined in this book support duplicates.

    0 讨论(0)
  • 2020-11-29 16:09

    Working on a red-black tree implementation I was getting problems validating the tree with multiple keys until I realized that with the red-black insert rotation, you have to loosen the constraint to

    left <= root <= right

    Since none of the documentation I was looking at allowed for duplicate keys and I didn't want to rewrite the rotation methods to account for it, I just decided to modify my nodes to allow for multiple values within the node, and no duplicate keys in the tree.

    0 讨论(0)
  • 2020-11-29 16:13

    Any definition is valid. As long as you are consistent in your implementation (always put equal nodes to the right, always put them to the left, or never allow them) then you're fine. I think it is most common to not allow them, but it is still a BST if they are allowed and place either left or right.

    0 讨论(0)
  • 2020-11-29 16:18

    Many algorithms will specify that duplicates are excluded. For example, the example algorithms in the MIT Algorithms book usually present examples without duplicates. It is fairly trivial to implement duplicates (either as a list at the node, or in one particular direction.)

    Most (that I've seen) specify left children as <= and right children as >. Practically speaking, a BST which allows either of the right or left children to be equal to the root node, will require extra computational steps to finish a search where duplicate nodes are allowed.

    It is best to utilize a list at the node to store duplicates, as inserting an '=' value to one side of a node requires rewriting the tree on that side to place the node as the child, or the node is placed as a grand-child, at some point below, which eliminates some of the search efficiency.

    You have to remember, most of the classroom examples are simplified to portray and deliver the concept. They aren't worth squat in many real-world situations. But the statement, "every element has a key and no two elements have the same key", is not violated by the use of a list at the element node.

    So go with what your data structures book said!

    Edit:

    Universal Definition of a Binary Search Tree involves storing and search for a key based on traversing a data structure in one of two directions. In the pragmatic sense, that means if the value is <>, you traverse the data structure in one of two 'directions'. So, in that sense, duplicate values don't make any sense at all.

    This is different from BSP, or binary search partition, but not all that different. The algorithm to search has one of two directions for 'travel', or it is done (successfully or not.) So I apologize that my original answer didn't address the concept of a 'universal definition', as duplicates are really a distinct topic (something you deal with after a successful search, not as part of the binary search.)

    0 讨论(0)
  • 2020-11-29 16:19

    If your binary search tree is a red black tree, or you intend to any kind of "tree rotation" operations, duplicate nodes will cause problems. Imagine your tree rule is this:

    left < root <= right

    Now imagine a simple tree whose root is 5, left child is nil, and right child is 5. If you do a left rotation on the root you end up with a 5 in the left child and a 5 in the root with the right child being nil. Now something in the left tree is equal to the root, but your rule above assumed left < root.

    I spent hours trying to figure out why my red/black trees would occasionally traverse out of order, the problem was what I described above. Hopefully somebody reads this and saves themselves hours of debugging in the future!

    0 讨论(0)
提交回复
热议问题