r/AskComputerScience • u/likejudo BSCS • Nov 29 '24
Red-Black Trees. Why can't a 3-node tree fulfill the conditions for RBT?
Challenge from instructor in Coursera Algorithms course.
see screenshot: https://imgur.com/a/4SKpX5y
If I color node #2 red, then it appears to me that all 3 conditions are met.
- root and leaves are Black
- Every Red node has two Black children.
- The Black height from any node is well defined and consistent.
I don't know what I am missing.
(in comparison, here is a different slide from his lecture with a RBT https://imgur.com/a/eUJW3S2)
2
Upvotes
3
u/Objective_Mine MSCS, CS Pro (10+) Nov 29 '24
If you colour node 2 red, its left child (nil leaf) and right child (node 3) both have to be black. Since nil leaves are considered black, both children of node 3 are also black, so the black height of node 2 is not consistent. (1 on its left subtree, 2 on its right one.)
2
u/johndcochran Nov 29 '24
Looking at your image, node 2 only has 1 child, which violates your condition of "Every Red node has two Black children".
The point that you're missing is that "nil" is not a child.
1
u/[deleted] Nov 29 '24
Keep it simple.
2 is sufficient.