TBST

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

struct Node {
    int key;
    struct Node *left;
    struct Node *right;
};

struct Node *newNode(int key) {
    struct Node *node = (struct Node *)malloc(sizeof(struct Node));
    node->key = key;
    node->left = NULL;
    node->right = NULL;
    return node;
}

struct Node *insert(struct Node *root, int key) {
    if (root == NULL) return newNode(key);
    if (key < root->key)
        root->left = insert(root->left, key);
    else if (key > root->key)
        root->right = insert(root->right, key);
    return root;
}

void preorder(struct Node *root) {
    if (root == NULL) return;
    printf("%d,", root->key);
    preorder(root->left);
    preorder(root->right);
}

int main() {
    char line[10000];
    fgets(line, sizeof(line), stdin);
    size_t len = strlen(line);
    if (len > 0 && line[len - 1] == '\n') {
        line[len - 1] = '\0';
    }
    struct Node *root = NULL;
    char *token = strtok(line, ",");
    while (token != NULL) {
        if (strlen(token) > 0) {
            int key = atoi(token);
            root = insert(root, key);
        }
        token = strtok(NULL, ",");
    }
    preorder(root);
    printf("\n");
    return 0;
}

 

posted @ 2025-11-19 13:26  我不是青山  阅读(0)  评论(0)    收藏  举报