Menu
Coddy logo textTech

Denge Faktörünü Al

Coddy'nin AVL Tree - Veri Yapıları Serisi #10 kursunda ders 6 / 16.

Bir düğümün denge faktörü getHeight(node.left) - getHeight(node.right) değeridir. Pozitif bir sayı sol tarafın daha yüksek olduğu, negatif bir sayı sağ tarafın daha yüksek olduğu ve 0 ise her iki tarafın eşit olduğu anlamına gelir.

Bir düğüm, denge faktörü -1, 0 veya 1 olduğu sürece dengeli kabul edilir. Bu aralığın dışındaki herhangi bir değer (2 veya daha fazla, veya -2 veya daha az), bir rotasyonu tetikleyen durumdur.

challenge icon

Görev

Başlangıç

AVLTree üzerinde, node null ise 0 dönen, aksi takdirde getHeight(node.left) - getHeight(node.right) sonucunu dönen bir getBalance(node) metodu yazın.

Kendin dene

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "avltree.h"

static Node* mkNodeWithHeight(int h) {
    Node* n = Node_create(0);
    n->height = h;
    return n;
}

int main(void) {
    AVLTree* tree = AVLTree_create();
    char line[256];
    while (fgets(line, sizeof(line), stdin) != NULL) {
        line[strcspn(line, "\r\n")] = '\0';
        char lTok[64];
        char rTok[64];
        sscanf(line, "%63s %63s", lTok, rTok);
        Node* root = Node_create(0);
        root->left = NULL;
        if (strcmp(lTok, "null") != 0) {
            root->left = mkNodeWithHeight(atoi(lTok));
        }
        root->right = NULL;
        if (strcmp(rTok, "null") != 0) {
            root->right = mkNodeWithHeight(atoi(rTok));
        }
        printf("%d\n", AVLTree_getBalance(tree, root));
    }
    return 0;
}

AVL Tree - Veri Yapıları Serisi #10 bölümündeki tüm dersler