summaryrefslogtreecommitdiff
path: root/bin-trees/task19.cpp
blob: c2f40bb014c0b65250b2b39bb7f502e346c98dab (plain)
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
#include <iostream>
#include <string>

#include "tree.h"

using namespace std;

void helper(tree *&t, int *sum, int *cnt)
{
    if (!t) return;

    if (t->left == NULL && t->right == NULL)
    {
        *sum += t->inf;
        (*cnt)++;
    }

    helper(t->left, sum, cnt);
    helper(t->right, sum, cnt);
}

float solve(tree *&t)
{
    int sum = 0;
    int cnt = 0;
    helper(t, &sum, &cnt);
    return sum * 1.0 / cnt;
}

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));

    float res = solve(t);
    cout << "Среднее арифметическое листьев равно " << res << endl;

    return 0;
}