Red Black Tree ~ 1 Child Deletes

最后都变了- 提交于 2019-12-07 06:59:17

问题


Is it ever possible for a red parent node to have just ONE black child node? I have been playing around with the Red/Black Tree simulator online and I can't manage to get a case of this to happen.

The reason behind asking this is I believe I have an unnecessary IF in my code...

if (temp_node->color == BLACK && node->color == RED)
{
    node->color = BLACK;
    global_violation = false;
}

Thanks for any Feedback!!


回答1:


No, this isn't possible.

Remember, that in a red/black tree, all paths from the root of the tree off of the tree must pass through the same number of black nodes (that's one of the red/black tree invariants).

If you have a red node x with one black child y, it cannot have another red child (since that breaks the red/black invariant that red nodes can't have red children).

This means that a path through x to the missing child will pass through at least one fewer black node than the path through x, then to y, and then off the tree from there, breaking the red/black tree invariants.




回答2:


Yes, it is possible. Following is a case wherein you CAN have a red node with a single black child without breaking any rules:

Step 1) Insert: 10, 7, 40, 3, 8, 30, 45, 1, 5, 20, 35, 60, 25. Following shows the red-black tree BEFORE deletion of node 30:

Step 2) Delete 30 (a degree 2 red node). Following shows the red-black tree AFTER deletion of node 30:

Assuming replacement strategy as least in the right subtree, node that replaces 30 is 35.

Now, when you do replace a node, I believe the replacement node will inherit the color of the replaced node as well. This means, 35 is red.

This yields a tree wherein, 35 is a red node with a single black child.



来源:https://stackoverflow.com/questions/35262353/red-black-tree-1-child-deletes

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