Skip to content

Instantly share code, notes, and snippets.

@atiedebee
Last active April 17, 2025 13:44
Show Gist options
  • Save atiedebee/78a3568b295d69f8fabe8b78428b81fe to your computer and use it in GitHub Desktop.
Save atiedebee/78a3568b295d69f8fabe8b78428b81fe to your computer and use it in GitHub Desktop.
Pretty Binary tree printing
struct Node{
int val;
struct Node* l;
struct Node* r;
};
// call with (head, 0, 0)
static void printtree(struct Node* h, size_t depth, int leaf){
static int stack[128];
stack[depth] = leaf;
unsigned int k = 0;
for( int i = 0; i < depth; i++ ){
k |= (stack[i+1] == -stack[i])<<i;
}
if( h->l ){
printtree(h->l, depth+1, 1);
}
for( int j = 0; j < depth; j++ ){
if( (k>>j)&1 ){
switch( stack[j] ){
case 1: printf(" / "); break;
case 0: printf(" "); break;
case -1: printf(" \\ "); break;
}
}else{
printf(" ");
}
}
if( leaf == 1 ){
printf(" /");
}
else if( leaf == -1 ){
printf(" \\");
}else{
printf("--");
}
if( h->v == UINT16_MAX ){ // invalid whatever, not a leaf node
printf("-----<\n");
}else{
printf("- %02x\n", h->v);
}
if( h->r ){
printtree(h->r, depth+1, -1);
}
}
@atiedebee
Copy link
Author

                               /- 05
                        /-----<
                       /      \       /- 06
                       /       \-----<
                       /             \       /- 03
                       /              \-----<
                       /                    \       /- 07
                       /                     \-----<
                       /                            \- 09
                 /-----<
                /      \       /- 0e
                /       \-----<
                /             \       /- 04
                /              \-----<
                /                    \              /- 0b
                /                    \       /-----<
                /                    \      /      \       /- 00
                /                    \      /       \-----<
                /                    \      /              \- 02
                /                     \-----<
                /                            \- 01
          /-----<
         /      \       /- 0d
         /       \-----<
         /              \- 0c
-------<
         \              /- 0a
         \       /-----<
         \      /       \- 08
          \-----<
                 \- 0f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment