问题
I want to insert 7 items in my tree -3, -2, -1, 0, 1, 2 and 3. I get a well balanced tree of height 3 without doing rotations when I insert by this order: 0, -2, 2, -1, 1, -3, 3. But when I insert all items in ascending order, the right part of the root node does rebalancing, but the left part of the the root node doesn't. All rebalancing algorithms I have seen, do rebalancing from the inserted node up to the root node, and then they stop. Shouldn't they continue to the opposite part of the root node? And I have the feeling it gets worse, if I insert lots of items in ascending order (like 0 to 100). At the end tree is balanced, but is not height optimized.
回答1:
None of the balanced binary-search trees (R/B trees, AVL trees, etc.) provide absolute balancing, that is none of them provide minimal possible height. This is because it is not possible to do such a "complete" rebalancing fast. If we want always to keep the height minimal possible, a heavy rebalancing will often be required on tree operations, and therefore the rebalancing will not work in O(log N)
. As a result, all the operations (insert, update, delete, etc) will not work in O(log N)
time also, and this will destroy the whole idea of balanced tree.
What balanced trees do guarantee is a not-so-strict requirement on tree height: the tree height is O(log N)
, that is C*log N
for some constant C
. So the tree is not guaranteed to be ideally balanced, but the balance will always be not far from ideal.
来源:https://stackoverflow.com/questions/30501851/red-black-trees-rebalancing