From f825070a18f1f007b55cbc92f5ee0325d0b5cf28 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 18 Mar 2021 20:10:40 +0400 Subject: =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=2014=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=B4=D0=B0=D1=87=D1=83=20=D0=B2=20=D0=B4=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=B2=D1=8C=D1=8F=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin-trees/task14.cpp | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 bin-trees/task14.cpp (limited to 'bin-trees') diff --git a/bin-trees/task14.cpp b/bin-trees/task14.cpp new file mode 100644 index 0000000..0891a9a --- /dev/null +++ b/bin-trees/task14.cpp @@ -0,0 +1,65 @@ +#include +#include + +#include "tree.h" + +using namespace std; + +void helper(tree *&t, int k, int depth, int *sum) +{ + if (!t) return; + + if (depth == k) + *sum += t->inf; + + if (depth < k) + { + helper(t->left, k, depth + 1, sum); + helper(t->right, k, depth + 1, sum); + } +} + +int solve(tree *&t, int k) +{ + int sum = 0; + helper(t, k, 0, &sum); + return sum; +} + +void create(tree *&t, int n, tree *parent) +{ + if (n > 0) + { + int x; + cin >> x; + t = node(x); + t->parent = parent; + + int nl = n / 2; + int nr = n - nl - 1; + + create(t->left, nl, t); + create(t->right, nr, t); + } +} + +int main() +{ + int n; + cout << "Введите количество узлов: "; + cin >> n; + tree *t = new tree; + cout << "Введите содержимое узлов:" << endl; + create(t, n, NULL); + + print(t, log(n) / log(2)); + + cout << "Введите число k: "; + int k; + cin >> k; + + int res = solve(t, k); + cout << "Сумма узлов на уровне k равна " << res << endl; + + return 0; +} -- cgit v1.2.3