diff options
| author | Andrew <saintruler@gmail.com> | 2021-03-18 20:10:40 +0400 |
|---|---|---|
| committer | Andrew <saintruler@gmail.com> | 2021-03-18 20:10:40 +0400 |
| commit | f825070a18f1f007b55cbc92f5ee0325d0b5cf28 (patch) | |
| tree | ed0f9e08b2f21ffb703c1a43d65e1bb620e2593e | |
| parent | db8aa3da4db1bd311e014ff6b1f27e7a1c79950f (diff) | |
Добавил 14 задачу в деревьях
| -rw-r--r-- | bin-trees/task14.cpp | 65 |
1 files changed, 65 insertions, 0 deletions
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 <iostream> +#include <string> + +#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; +} |