规则 Rules

  • 每个结点要么是红的要么是黑的
  • 根结点永远是黑的
  • 新插入的结点是红的
  • 所有从根结点到叶结点的路径拥有相同数量的黑结点(平衡)
  • 所有路径不能有连续的红结点
  • 空节点被视作黑结点(主要用于判断新结点的叔结点时)

平衡操作 Rebalance

  • 当新结点的叔结点是红色的,做 Color Flip 操作 3 1 5 insert 7 3 1 5 7 color flip 3 1 5 7 correct root 3 1 5 7
  • 当新结点的叔结点是黑色的,做 Rotate 操作 (父黑子红) 3 1 5 7 insert 6 3 1 5 7 6 RL Rotate 3 1 6 5 7 fix color 3 1 6 5 7 rotate: 调整爷父孙节点,使得它们有序

树旋转 Tree Rotation

移动爷结点使得树回到平衡的状态 Moving grandparent clockwise or counter-clockwise to relbance the tree. 9 6 4 Right Rotate 6 4 9 4 6 9 Left Rotate 6 4 9 4 8 6 Right Rotate of parent 4 6 8 Left Rotate of grandparent 6 4 8