From b1c6da09fcc9b41b3d1f39f6e1600cca88874157 Mon Sep 17 00:00:00 2001 From: Marat Izmailov Date: Mon, 18 Nov 2024 12:51:45 +0000 Subject: [PATCH] Add a4/program.c --- a4/program.c | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 a4/program.c diff --git a/a4/program.c b/a4/program.c new file mode 100644 index 0000000..7605406 --- /dev/null +++ b/a4/program.c @@ -0,0 +1,61 @@ +#include + +int main() { + int arr[100]; // Array to store the input numbers + int n = 0; // To keep track of how many numbers we have + + // Input the numbers + while (scanf("%d", &arr[n]) == 1) { + n++; + } + + // Check if the array is a min-heap + int isHeap = 1; // Flag to indicate whether it's a min-heap + + for (int i = 0; i < n; i++) { + int left = 2 * i + 1; + int right = 2 * i + 2; + + // Check if left child exists and if it is smaller than the parent + if (left < n && arr[i] > arr[left]) { + isHeap = 0; // Not a min-heap + break; + } + + // Check if right child exists and if it is smaller than the parent + if (right < n && arr[i] > arr[right]) { + isHeap = 0; // Not a min-heap + break; + } + } + + if (isHeap == 0) { + printf("Nie je kopa.\n"); // If it's not a min-heap, print this + return 0; // End the program + } + + // If it's a min-heap, print the binary tree in preorder + printf("Je to taka kopa:\n"); + + // Function to print tree in preorder + void printPreorder(int i, int level) { + if (i >= n) { + return; // Stop if index is out of bounds + } + + // Print the current node with spaces for the level + for (int j = 0; j < level; j++) { + printf(" "); + } + printf("%d\n", arr[i]); + + // Recursively print left and right children + printPreorder(2 * i + 1, level + 1); // Left child + printPreorder(2 * i + 2, level + 1); // Right child + } + + // Start with the root node + printPreorder(0, 0); + + return 0; +}