Menu
CoddyTech

带子节点的节点

Coddy 二叉树:数据结构系列第 3 篇 课程的第 4 课,共 13 课。

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 篇中的所有课

自己练习: C 在线编译器