BST

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

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

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

typedef struct QNode {
    Node* tree;
    struct QNode* next;
} QNode;

typedef struct Queue {
    QNode* front;
    QNode* rear;
} Queue;

Queue* createQueue() {
    Queue* q = (Queue*)malloc(sizeof(Queue));
    q->front = NULL;
    q->rear = NULL;
    return q;
}

void enqueue(Queue* q, Node* tree) {
    QNode* newQ = (QNode*)malloc(sizeof(QNode));
    newQ->tree = tree;
    newQ->next = NULL;
    if (q->rear == NULL) {
        q->front = newQ;
        q->rear = newQ;
    } else {
        q->rear->next = newQ;
        q->rear = newQ;
    }
}

Node* dequeue(Queue* q) {
    if (q->front == NULL) return NULL;
    QNode* temp = q->front;
    Node* tree = temp->tree;
    q->front = q->front->next;
    if (q->front == NULL) q->rear = NULL;
    free(temp);
    return tree;
}

int isEmpty(Queue* q) {
    return q->front == NULL;
}

int main() {
    char buf[1024];
    fgets(buf, sizeof(buf), stdin);
    int N = atoi(buf);

    char line[1024];
    fgets(line, sizeof(line), stdin);

    fgets(buf, sizeof(buf), stdin);
    int K = atoi(buf);

    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, ",");
    }

    if (root == NULL) {
        printf("-1\n");
        return 0;
    }

    Queue* q = createQueue();
    int nodes[20];
    int count = 0;
    int current_level = 1;

    enqueue(q, root);
    enqueue(q, NULL);

    while (!isEmpty(q)) {
        Node* curr = dequeue(q);
        if (curr == NULL) {
            current_level++;
            if (!isEmpty(q)) {
                enqueue(q, NULL);
            } else {
                break;
            }
            continue;
        }

        if (current_level == K) {
            nodes[count++] = curr->key;
        }

        if (curr->left) enqueue(q, curr->left);
        if (curr->right) enqueue(q, curr->right);
    }

    if (count == 0) {
        printf("-1\n");
    } else {
        for (int i = 0; i < count; i++) {
            printf("%d,", nodes[i]);
        }
        printf("\n");
    }
    return 0;
}

 

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