Binary Search Tree

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

// Definition of the Binary Search Tree Node
typedef struct Node {
    int key;
    struct Node *left;
    struct Node *right;
} Node;

// Function to create a new node
Node* createNode(int key) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->key = key;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

// Function to insert a key into the BST
// Preserves properties: Left < Root < Right
Node* insert(Node* root, int key) {
    // If the tree/subtree is empty, return a new node
    if (root == NULL) {
        return createNode(key);
    }

    // Recurse down the tree
    if (key < root->key) {
        root->left = insert(root->left, key);
    } else if (key > root->key) {
        root->right = insert(root->right, key);
    }
    // If key is equal, do nothing (keys are distinct)

    return root;
}

// Recursive function to print nodes at a specific level
// Traverse Left to Right
void printNodesAtLevel(Node* root, int currentLevel, int targetLevel, int* found) {
    if (root == NULL) {
        return;
    }

    // If we reached the target level
    if (currentLevel == targetLevel) {
        printf("%d,", root->key);
        *found = 1; // Mark that we found at least one node
        return;
    }

    // If not at target level yet, recurse deeper
    // Left child first ensures left-to-right output order
    printNodesAtLevel(root->left, currentLevel + 1, targetLevel, found);
    printNodesAtLevel(root->right, currentLevel + 1, targetLevel, found);
}

int main() {
    int n;          // Number of elements
    int val;        // Temporary variable for input values
    int level;      // Target level to print
    char delimiter; // To consume the comma
    Node* root = NULL;

    // 1. Read the number of sequence
    if (scanf("%d", &n) != 1) return 0;

    // 2. Read the sequence of integers
    // Note: The input format includes commas (e.g., "32,3,56,...")
    for (int i = 0; i < n; i++) {
        scanf("%d", &val);
        // Consume the comma or trailing character
        // We use a loop or getchar to safely skip the delimiter
        do {
            delimiter = getchar();
        } while (delimiter != ',' && delimiter != '\n' && delimiter != EOF);
        
        root = insert(root, val);
    }

    // 3. Read the target level
    scanf("%d", &level);

    // 4. Output the nodes at the specific level
    int found = 0; // Flag to check if any node exists at that level
    
    // Root is at level 1
    printNodesAtLevel(root, 1, level, &found);

    // If no nodes were found at the level, output -1
    if (!found) {
        printf("-1");
    }

    return 0;
}

 

posted @ 2025-12-24 09:58  我不是青山  阅读(1)  评论(0)    收藏  举报