Menu
Coddy logo textTech

Node with Sons

Урок 4 из 13 курса Бинарное дерево — Серия «Структуры данных» №3 на Coddy.

challenge icon

Задание

Легко

Добавьте в Node поддержку двух дочерних узлов (левого и правого). Конструктор должен инициализировать оба значения как null/None/и т.д. Добавьте методы getLeft / setLeft и getRight / setRight.

Попробуйте сами

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

int main() {
    Node n;
    Node_init(&n);
    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, "setValue") == 0) {
            char* arg = strtok(NULL, " \t");
            if (arg) Node_setValue(&n, atoi(arg));
        }
        if (strcmp(cmd, "getValue") == 0) {
            printf("%d\n", Node_getValue(&n));
        }
        if (strcmp(cmd, "setLeft") == 0) {
            char* arg = strtok(NULL, " \t");
            Node* c = Node_new();
            Node_setValue(c, atoi(arg));
            Node_setLeft(&n, c);
        }
        if (strcmp(cmd, "getLeftValue") == 0) {
            printf("%d\n", Node_getValue(Node_getLeft(&n)));
        }
        if (strcmp(cmd, "setRight") == 0) {
            char* arg = strtok(NULL, " \t");
            Node* c = Node_new();
            Node_setValue(c, atoi(arg));
            Node_setRight(&n, c);
        }
        if (strcmp(cmd, "getRightValue") == 0) {
            printf("%d\n", Node_getValue(Node_getRight(&n)));
        }
    }
    return 0;
}

Все уроки раздела Бинарное дерево — Серия «Структуры данных» №3