Last active
April 17, 2025 13:44
-
-
Save atiedebee/78a3568b295d69f8fabe8b78428b81fe to your computer and use it in GitHub Desktop.
Pretty Binary tree printing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Author
atiedebee
commented
Apr 17, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment