internal static void RemoveNode(AVLNode node, AVLTree <TKey, TValue> tree) { if (node.right == null && node.left == null) // no children { if (node.head == null) // was the top node { tree.head = null; } else { if (node.isLeft) { node.head.left = null; node.head._depthL = 0; } else { node.head.right = null; node.head._depthR = 0; } AVLNode.BalanceSelfBubbleUp(node.head, tree); } } else if (node.right == null || node.left == null) // one child { AVLNode child = node.right != null ? node.right : node.left; if (node.head == null) // was the top node { tree.head = child; child.head = null; } else { child.isLeft = node.isLeft; if (node.isLeft) { node.head.left = child; child.head = node.head; node.head._depthL -= 1; } else { node.head.right = child; child.head = node.head; node.head._depthR -= 1; } AVLNode.BalanceSelfBubbleUp(node.head, tree); } } else // two children :O { AVLNode child = node.right, childhead = node.head; while (child.left != null) { childhead = child; child = child.left; } if (childhead != node.head) { if (child.right != null) { childhead.left = child.right; child.right.head = childhead; child.right.isLeft = true; childhead._depthL--; } else { childhead.left = null; childhead._depthL = 0; } child.right = node.right; } child.left = node.left; child.left.head = child; child.head = node.head; child.isLeft = node.isLeft; if (node.head == null) { tree.head = child; } else { if (node.isLeft) { node.head.left = child; } else { node.head.right = child; } } if (childhead == node.head) { AVLNode.BalanceSelfBubbleUp(child, tree); } else { child.right.head = child; AVLNode.BalanceSelfBubbleUp(childhead, tree); } } tree.count--; }
private void Rebalance(AVLTree <TKey, TValue> tree) { if (Math.Abs(balance) > 2) { if (balance < -2) { left.Rebalance(tree); } else { right.Rebalance(tree); } } if (balance > 1) { // 5_2 | 7 // 2 7_1 | 5 8 // 6 8_1 | 2 6 9 // 9 | // 5 | 5 // 2 6 | 3 6 // 3 | 2 4 // 4 | // 5 | 5 | 7 // 2 8 | 2 7 | 5 8 // 7 9 | 6 8 | 2 6 9 // 6 | 9 | if (right.balance > 0) { RotateLeft(right, tree); } else { RotateRight(right.left, tree); RotateLeft(right, tree); } } else if (balance < -1) { // 5 | 5 // 4 9 | 4 8 // 8 | 7 9 // 7 | // 5 | 5 | 3 // 1 6 | 3 6 | 1 5 // 0 3 | 1 4 | 0 4 6 // 4 | 0 | if (left.balance < 0) { RotateRight(left, tree); } else { RotateLeft(left.right, tree); RotateRight(left, tree); } } #if TEST checkNodeSelf(this); #endif }