-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.c
More file actions
88 lines (75 loc) · 1.47 KB
/
tree.c
File metadata and controls
88 lines (75 loc) · 1.47 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//Implements a list of numbers as a binary search tree
# include <cs50.h>
# include <sdio.h>
# include <stdlib.h>
//represents a node
typedef struct node
{
int number;
struct node *left;
struct node *right;
}
node;
void free_tree(node *root);
void print_tree(node *root);
int main (void)
{
//Tree of size 0
node *tree = NULL;
//Add number to list
node *n = malloc(sizeof(node));
if (n == NULL)
{
return 1;
}
n->number = 2;
n->left = NULL;
n->right = NULL;
tree = n;
//Add number to list
n = malloc(sizeof(node));
if (n == NULL)
{
//Free memory
return 1;
}
n->number = 1;
n->left = NULL;
n->right = NULL;
tree->left =n;
//Add number to list
n = malloc(sizeof(node));
if (n == NULL)
{
return 1;
}
n->number = 3;
n->left = NULL;
n->right = NULL;
tree->right =n;
//Print Tree
print_tree(tree);
//Free tree
free_tree(tree);
}
void free_tree(node *root)
{
if (root == NULL)
{
return;
}
free_tree(root->left);
free_tree(root->right);
free(root);
}
void print_tree(node *root)
{
//This is a safety if the number equals noting (i.e. NULL) it returns nothing
if (root == NULL)
{
return;
}
print_tree(root->left);
printf("%i\n", root->number);
print_tree(root->right);
}