From 1def797a53a6685af31efab783ad0dbee5f7eaeb Mon Sep 17 00:00:00 2001 From: VIliam Date: Mon, 18 Nov 2024 14:37:46 +0100 Subject: [PATCH] a4 --- a4/program.c | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/a4/program.c b/a4/program.c index e69de29..9c595fe 100644 --- a/a4/program.c +++ b/a4/program.c @@ -0,0 +1,61 @@ +#include +#include + +// Funkcia na overenie, či je pole binárna minimálna kopa +bool is_min_heap(int arr[], int n) { + for (int i = 0; i <= (n - 2) / 2; i++) { + int left = 2 * i + 1; + int right = 2 * i + 2; + + if (left < n && arr[i] > arr[left]) { + return false; + } + if (right < n && arr[i] > arr[right]) { + return false; + } + } + return true; +} + +// Funkcia na vypísanie stromu v preorder poradí +void preorder(int arr[], int n, int index, int level) { + if (index >= n) { + return; + } + for (int i = 0; i < level; i++) { + printf(" "); + } + printf("%d\n", arr[index]); + + preorder(arr, n, 2 * index + 1, level + 1); // Ľavý syn + preorder(arr, n, 2 * index + 2, level + 1); // Pravý syn +} + +int main() { + int arr[100], n = 0; + char input[1000]; + + // Načítanie vstupu + if (fgets(input, sizeof(input), stdin)) { + char *ptr = input; + while (sscanf(ptr, "%d", &arr[n]) == 1) { + n++; + while (*ptr != ' ' && *ptr != '\0') { + ptr++; + } + if (*ptr == ' ') { + ptr++; + } + } + } + + // Skontrolovanie, či je to binárna kopa + if (is_min_heap(arr, n)) { + printf("Je to taka kopa:\n"); + preorder(arr, n, 0, 0); + } else { + printf("Nie je kopa.\n"); + } + + return 0; +}