void balance1(Node* p, bool& h) { Node* p1, * p2; short b1, b2; if (p == NULL) return;…
- User
void balance1(Node* p, bool& h) { Node* p1, * p2; short b1, b2; if (p == NULL) return; switch (p->balance) { case -1: p->balance = 0; break; case 0: p->balance = 1; h = true; break; case 1: // балансировка p1 = p->right; b1 = p1->balance; if (b1 >= 0) // R-поворот { p->right = p1->left; p1->left = p; if (b1 == 0) { p->balance = 1; p1->balance = -1; h = false; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // RL-поворот { p2 = p1->left; b2 = p2->balance; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (b2 == 1) p->balance = -1; else p->balance = 0; if (b2 == -1) p1->balance = 1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void balance2(Node* p, bool& h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case 1: p->balance = 0; break; case 0: p->balance = -1; h = true; break; case -1: p1 = p->left; b1 = p1->balance; if (b1 <= 0) // L-поворот { p->left = p1->right; p1->right = p; if (b1 == 0) { p->balance = -1; p1->balance = 1; h = false; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // LR-поворот { p2 = p1->right; b2 = p2->balance; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (b2 == -1) p->balance = 1; else p->balance = 0; if (b2 == 1) p1->balance = -1; else p1->balance = 0; p = p2; p2->balance = 0; } } }
code - Assistant
This code snippet shows functions for balancing a AVL Tree during deletion of a node. Here are the main points:
- The
balance1function is responsible for balancing the AVL tree after a node is deleted from the left subtree of a node. - The
balance2function is responsible for balancing the AVL tree after a node is deleted from the right subtree of a node. - The
deletfunction is the main function for deleting a node from the AVL tree. It checks for the node to be deleted, recursively calls itself to traverse the tree, and balances the tree usingbalance1andbalance2functions after deletion. - In case a node has both left and right children, the code finds the "in-order successor" node, swaps its data with the node to be deleted, and then deletes the in-order successor node.
- The code also checks for different cases of deletion (node with no children, node with only left child, node with only right child) and handles them accordingly.
- After deletion, if the tree needs balancing (when is true), it checks the balance factor of the nodes and performs rotations to balance the tree.
- The