-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree_print.c
99 lines (92 loc) · 2.21 KB
/
binary_tree_print.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
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "binary_trees.h"
/* Original code from http://stackoverflow.com/a/13755911/5184480 */
/**
* print_t - Stores recursively each level in an array of strings
*
* @tree: Pointer to the node to print
* @offset: Offset to print
* @depth: Depth of the node
* @s: Buffer
*
* Return: length of printed tree after process
*/
static int print_t(const binary_tree_t *tree, int offset, int depth, char **s)
{
char b[6];
int width, left, right, is_left, i;
if (!tree)
return (0);
is_left = (tree->parent && tree->parent->left == tree);
width = sprintf(b, "(%03d)", tree->n);
left = print_t(tree->left, offset, depth + 1, s);
right = print_t(tree->right, offset + left + width, depth + 1, s);
for (i = 0; i < width; i++)
s[depth][offset + left + i] = b[i];
if (depth && is_left)
{
for (i = 0; i < width + right; i++)
s[depth - 1][offset + left + width / 2 + i] = '-';
s[depth - 1][offset + left + width / 2] = '.';
}
else if (depth && !is_left)
{
for (i = 0; i < left + width; i++)
s[depth - 1][offset - width / 2 + i] = '-';
s[depth - 1][offset + left + width / 2] = '.';
}
return (left + width + right);
}
/**
* _height - Measures the height of a binary tree
*
* @tree: Pointer to the node to measures the height
*
* Return: The height of the tree starting at @node
*/
static size_t _height(const binary_tree_t *tree)
{
size_t height_l;
size_t height_r;
height_l = tree->left ? 1 + _height(tree->left) : 0;
height_r = tree->right ? 1 + _height(tree->right) : 0;
return (height_l > height_r ? height_l : height_r);
}
/**
* binary_tree_print - Prints a binary tree
*
* @tree: Pointer to the root node of the tree to print
*/
void binary_tree_print(const binary_tree_t *tree)
{
char **s;
size_t height, i, j;
if (!tree)
return;
height = _height(tree);
s = malloc(sizeof(*s) * (height + 1));
if (!s)
return;
for (i = 0; i < height + 1; i++)
{
s[i] = malloc(sizeof(**s) * 255);
if (!s[i])
return;
memset(s[i], 32, 255);
}
print_t(tree, 0, 0, s);
for (i = 0; i < height + 1; i++)
{
for (j = 254; j > 1; --j)
{
if (s[i][j] != ' ')
break;
s[i][j] = '\0';
}
printf("%s\n", s[i]);
free(s[i]);
}
free(s);
}