forked from tamberg/fhnw-syspr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree_v2.c
61 lines (48 loc) · 1.27 KB
/
tree_v2.c
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
#include <stdio.h>
#include <stdlib.h>
struct node {
char *label;
struct node *left;
struct node *right;
};
int main(void) {
// allocate nodes, on the heap
struct node *ll = malloc(sizeof(struct node));
ll->label = "left left";
ll->left = NULL;
ll->right = NULL;
struct node *lr = malloc(sizeof(struct node));
lr->label = "left right";
lr->left = NULL;
lr->right = NULL;
struct node *l = malloc(sizeof(struct node));
l->label = "left";
l->left = ll;
l->right = lr;
struct node *r = malloc(sizeof(struct node));
r->label = "right";
r->left = NULL;
r->right = NULL;
struct node *root = malloc(sizeof(struct node));
root->label = "root";
root->left = l;
root->right = r;
// print labels, depth-first
printf("%s\n", root->label);
printf("%s\n", root->left->label);
printf("%s\n", root->left->left->label);
printf("%s\n", root->left->right->label);
printf("%s\n", root->right->label);
// free nodes, leaves-first
free(root->left->left);
root->left->left = NULL;
free(root->left->right);
root->left->right = NULL;
free(root->left);
root->left = NULL;
free(root->right);
root->right = NULL;
free(root);
root = NULL;
return 0;
}