File: binary_tree_malloc.c

package info (click to toggle)
datatype99 1.6.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 476 kB
  • sloc: ansic: 1,071; sh: 43; makefile: 6
file content (59 lines) | stat: -rw-r--r-- 1,263 bytes parent folder | download | duplicates (2)
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
// The binary_tree.c counterpart that allocates & releases trees using malloc & free.

#include <datatype99.h>

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// clang-format off
datatype(
    BinaryTree,
    (Leaf, int),
    (Node, BinaryTree *, int, BinaryTree *)
);
// clang-format on

BinaryTree *alloc_tree(BinaryTree tree) {
    BinaryTree *res = malloc(sizeof(*res));
    assert(res);
    memcpy((void *)res, (const void *)&tree, sizeof(tree));
    return res;
}

void destroy_tree(BinaryTree *tree) {
    ifLet(*tree, Node, lhs, _, rhs) {
        destroy_tree(*lhs);
        destroy_tree(*rhs);
    }

    free(tree);
}

int sum(const BinaryTree *tree) {
    match(*tree) {
        of(Leaf, x) return *x;
        of(Node, lhs, x, rhs) return sum(*lhs) + *x + sum(*rhs);
    }

    // Invalid input (no such variant).
    return -1;
}

#define TREE(tree)                alloc_tree(tree)
#define NODE(left, number, right) TREE(Node(left, number, right))
#define LEAF(number)              TREE(Leaf(number))

int main(void) {
    BinaryTree *tree = NODE(NODE(LEAF(1), 2, NODE(LEAF(3), 4, LEAF(5))), 6, LEAF(7));

    /*
     * Output:
     * 28
     */
    printf("%d\n", sum(tree));
    destroy_tree(tree);

    return 0;
}