1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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;
}
|