-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbintree.c
87 lines (71 loc) · 1.69 KB
/
bintree.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
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
// Harris Ransom
// C Binary Tree
// Based on video by Jacob Sorber
#include <stdio.h>
#include <stdlib.h>
#define TREE_SIZE 5
typedef struct treenode {
int value;
struct treenode *left;
struct treenode *right;
} treenode;
// Creates new unconnected tree node
treenode *createnode(int value) {
treenode *result = malloc(sizeof(treenode));
if (result != NULL) {
result->left = NULL;
result->right = NULL;
result->value = value;
}
return result;
}
// Outputs specified number of tabs
void printTabs(int numTabs) {
for (int i = 0; i < numTabs; i++) {
printf("\t");
}
}
// Recursively prints out tree
void printTree(treenode *root, int level) {
if (root == NULL) {
printTabs(level);
printf("---<Empty>---\n");
return;
}
// Recursive Preorder Traversal
printTabs(level);
printf("value = %d\n", root->value);
printTabs(level);
printf("left\n");
printTree(root->left, level+1);
printTabs(level);
printf("right\n");
printTree(root->right, level+1);
printTabs(level);
printf("done\n");
}
// MAIN
int main() {
// Creates binary tree
treenode **tree = malloc(TREE_SIZE * sizeof(treenode));
for (int i = 0; i < TREE_SIZE; i++) {
tree[i] = createnode(10+i);
}
treenode *n1 = tree[0];
treenode *n2 = tree[1];
treenode *n3 = tree[2];
treenode *n4 = tree[3];
treenode *n5 = tree[4];
// Builds tree structure
n1->left = n2;
n1->right = n3;
n3->left = n4;
n3->right = n5;
// Outputs tree
printTree(tree[0], 0);
// Deletes tree
for (int i = 0; i < TREE_SIZE; i++) {
free(tree[i]);
}
return 0;
}