root/libbst/libbst_test.c

Revision 66, 1.4 KB (checked in by aqua, 4 years ago)

clean up print functions & move test stubs to libbst_test.c

Line 
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5#include <math.h>
6
7#include "libbst.h"
8
9/* print with pre-order traversal */
10void bst_porder_print( bst_ptr root, int depth, int* pos, char** buf ){
11
12        char tmp[4];
13       
14        if( root == NULL )
15                return;
16
17        /* traversal left child first */
18        if( root->left != NULL )
19                bst_porder_print( root->left, depth+1, pos, buf );
20       
21        /* traversal current node */
22        sprintf( tmp, "%3d", root->var );
23       
24        buf[depth][*pos] = tmp[0];
25        buf[depth][(*pos)+1] = tmp[1];
26        buf[depth][(*pos)+2] = tmp[2];
27       
28        (*pos) += 3;
29       
30        /* traversal right child last */
31        if( root->right != NULL )
32                bst_porder_print( root->right, depth+1, pos, buf );
33       
34}
35
36/* remove white spaces in right side of buf */
37void bst_rtrim( char* str ){
38
39        int i = strlen(str);
40       
41        while( str[--i] == ' ' && i > 0 );
42        str[i+1] = 0;
43
44}
45
46/* print */
47void bst_print( bst_ptr root, FILE* out ){
48
49        int level;
50        int i, size;
51
52        char** buf;
53       
54        level = bst_get_level( root );
55
56        /* if tree is empty, then return; */
57        if( level < 1 )
58                return;
59       
60        /* allocate buffer */
61        buf = (char**)malloc( sizeof(char*)*level );
62        size = sizeof(char) * 3 * ( pow(2,level) -1 );
63       
64        for( i = 0 ; i < level ; i++ ){
65                buf[i] = (char*)malloc(size);
66                memset( buf[i], ' ', size );
67        }
68
69        i = 0;
70        bst_porder_print( root, 0, &i,  buf );
71       
72        for( i = 0 ; i < level ; i++ ){
73                bst_rtrim( buf[i] );
74                fprintf( stdout, "%s\n", buf[i] );
75                free(buf[i]);
76        }
77        free(buf);
78
79}
80
81
Note: See TracBrowser for help on using the browser.