Menu
Coddy logo textTech

Get Height

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

Add a getHeight method to AVLTree that reads a node's stored height. The only trick is the null case: an empty subtree does not exist, so by convention its height is 0, one less than a real leaf's height of 1.

Routing every height lookup through this one method (instead of reading node.height directly everywhere) means the null check only has to be written once.

challenge icon

Challenge

Beginner

Write a method getHeight(node) on AVLTree that returns 0 if node is null, otherwise returns node.height.

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, "null") == 0) {
            printf("%d\n", AVLTree_getHeight(tree, NULL));
        }
        if (strcmp(line, "null") != 0) {
            int h;
            sscanf(line, "%d", &h);
            Node* n = Node_create(0);
            n->height = h;
            printf("%d\n", AVLTree_getHeight(tree, n));
        }
    }
    return 0;
}

All lessons in AVL Tree - Data Structures Series #10