Menu
Coddy logo textTech

Insert

Lesson 10 of 13 in Coddy's Binary Tree - Data Structures Series #3 course.

challenge icon

Challenge

Easy

Add to BinaryTree a method insert that takes an integer and inserts it into a binary search tree. (Values smaller than or equal to the current node go to the left subtree; greater values go to the right subtree.)

Try it yourself

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

int main() {
    BinaryTree bt;
    BinaryTree_init(&bt);
    char line[256];
    while (fgets(line, sizeof(line), stdin)) {
        line[strcspn(line, "\r\n")] = '\0';
        char* cmd = strtok(line, " \t");
        if (!cmd) continue;
        if (strcmp(cmd, "insert") == 0) {
            char* arg = strtok(NULL, " \t");
            if (arg) BinaryTree_insert(&bt, atoi(arg));
        }
        if (strcmp(cmd, "inOrderPrint") == 0) {
            BinaryTree_inOrderPrint(&bt);
        }
    }
    return 0;
}

All lessons in Binary Tree - Data Structures Series #3