Menu
Coddy logo textTech

סיבוב שמאלה

שיעור 8 מתוך 16 בקורס עץ AVL – סדרת מבני נתונים מס' 10 של Coddy.

סיבוב שמאלה הוא תמונת מראה של הסיבוב ימינה שכתבת זה עתה, ומשתמשים בו כשצידו הימני של צומת גבוה מדי. קרא לצומת הלא מאוזן x ולבן הימני שלו y. y הופך לשורש תת-העץ החדש, x הופך לבן השמאלי של y, ותת-העץ השמאלי הישן של y (T2) מחובר מחדש כבן הימני החדש של x.

אותו כלל חל גם על הגבהים: חשב מחדש תחילה את הגובה של x, ואז של y, מכיוון ש-x הוא כעת הצומת הנמוך יותר.

challenge icon

אתגר

קל

כתוב מתודה rotateLeft(x) במחלקה AVLTree. הגדר y = x.right ו-T2 = y.left. הגדר y.left = x ו-x.right = T2, חשב מחדש את הגובה של x ואז של y, והחזר את y כשורש תת-העץ החדש.

נסו בעצמכם

#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;
}

כל השיעורים ביחידה עץ AVL – סדרת מבני נתונים מס' 10

תרגלו בעצמכם: קומפיילר C אונליין