-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.c
46 lines (38 loc) · 1.19 KB
/
tree.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
#include <stdlib.h>
#include <stdio.h>
#include "tree.h"
// Helper method to initialize a newTreeNode
TreeNode newTreeNode(char symbol) {
TreeNode temp = (TreeNode) calloc (1, sizeof(struct node));
temp->symbol = symbol;
temp->freq = 1;
temp->left = NULL;
temp->right = NULL;
temp->parent = NULL;
return temp;
}
// Recurses through the tree, displaying children through indentation
void displayTreeHelper(TreeNode root, int indent) {
if(root == NULL) { return; }
int i;
for(i = 0; i < indent; i++) { printf(" "); }
// Print the node's symbol,
// unless it's a parent node, then print *
char temp;
if(root->symbol != 0) { temp = root->symbol; } else { temp = '*'; }
printf("[%c] : %d\n", temp, root->freq);
// Recurse on node's children
displayTreeHelper(root->left, indent + 3);
displayTreeHelper(root->right, indent + 3);
}
// Calls the recursive display function above
void displayTree(TreeNode root) {
displayTreeHelper(root, 0);
}
// Recursively frees a tree, takes its root as an argument
void freeTree(TreeNode root) {
if(root == NULL) { return; }
freeTree(root->left);
freeTree(root->right);
free(root);
}