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

后端 未结 12 916
慢半拍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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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!

提交回复
热议问题