Menu
Coddy logo textTech

Kth Smallest Element

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

The next challenges use the finished AVLTree class you just built, provided to you as a locked file. Each challenge ships a fresh solution file where you write a function that USES the tree.

An in-order traversal of any binary search tree (rotations don't change this) visits values in sorted order. So the kth smallest value is simply the element at index k - 1 of that traversal.

challenge icon

Challenge

Easy

Write a function kthSmallest(tree, k) that returns the kth smallest value in the tree (1-indexed). You may assume k is valid.

Try it yourself

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

int main(void) {
    AVLTree* tree = AVLTree_create();
    char line1[4096];
    fgets(line1, sizeof(line1), stdin);
    char* tok = strtok(line1, " \n");
    while (tok != NULL) {
        AVLTree_insert(tree, atoi(tok));
        tok = strtok(NULL, " \n");
    }
    char line2[256];
    fgets(line2, sizeof(line2), stdin);
    int p0 = atoi(strtok(line2, " \n"));
    int result = kthSmallest(tree, p0);
    printf("%d\n", result);
    return 0;
}

All lessons in AVL Tree - Data Structures Series #10