Left Rotate
Lesson 8 of 16 in Coddy's AVL Tree - Data Structures Series #10 course.
A left rotation is the mirror image of the right rotation you just wrote, used when a node's right side is too tall. Call the unbalanced node x and its right child y. y becomes the new subtree root, x becomes y's left child, and y's old left subtree (T2) is reattached as x's new right child.
Same rule for heights: recompute x first, then y, since x is now the lower node.
Challenge
EasyWrite a method rotateLeft(x) on AVLTree. Let y = x.right and T2 = y.left. Set y.left = x and x.right = T2, recompute the height of x then y, and return y as the new subtree root.
Try it yourself
#include <stdio.h>
#include <string.h>
#include "avltree.h"
int main(void) {
AVLTree* tree = AVLTree_create();
char line[256];
while (fgets(line, sizeof(line), stdin) != NULL) {
line[strcspn(line, "\r\n")] = '\0';
if (strcmp(line, "1") == 0) {
Node* x = Node_create(10);
x->height = 3;
Node* y = Node_create(20);
y->height = 2;
Node* t2 = Node_create(30);
t2->height = 1;
y->right = t2;
x->right = y;
Node* newRoot = AVLTree_rotateLeft(tree, x);
printf("%d %d %d %d\n", newRoot->value, newRoot->height, newRoot->left->value, newRoot->right->value);
}
if (strcmp(line, "2") == 0) {
Node* x = Node_create(20);
x->height = 3;
Node* y = Node_create(40);
y->height = 2;
y->left = Node_create(30);
y->left->height = 1;
y->right = Node_create(50);
y->right->height = 1;
x->left = Node_create(10);
x->left->height = 1;
x->right = y;
Node* newRoot = AVLTree_rotateLeft(tree, x);
printf("%d %d %d %d %d %d\n", newRoot->value, newRoot->height, newRoot->left->value, newRoot->right->value, newRoot->left->left->value, newRoot->left->right->value);
}
}
return 0;
}
All lessons in AVL Tree - Data Structures Series #10
2AVL Tree Project
Node ClassAVLTree Class