Menu
Coddy logo textTech

Get Balance Factor

Lesson 6 of 16 in Coddy's AVL Tree - Data Structures Series #10 course.

The balance factor of a node is getHeight(node.left) - getHeight(node.right). A positive number means the left side is taller, negative means the right side is taller, and 0 means they're even.

A node is considered balanced as long as its balance factor is -1, 0, or 1. Anything outside that range (2 or more, or -2 or less) is what triggers a rotation.

challenge icon

Challenge

Beginner

Write a method getBalance(node) on AVLTree that returns 0 if node is null, otherwise returns getHeight(node.left) - getHeight(node.right).

Try it yourself

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

All lessons in AVL Tree - Data Structures Series #10