问题
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