I want to print a binary tree like this:
50
├─25
| ├─10
| | ├─5
| | └─15
| └─40
| ├─35
| └─45
└─75
├─60
| ├─55
| └─65
└─90
├─85
└─95
But my program can only print like this:
50
├─25
| ├─10
| | ├─5
| | └─15
| └─40
| | ├─35
| | └─45
└─75
| ├─60
| | ├─55
| | └─65
| └─90
| | ├─85
| | └─95
I tried a lot to remove the rudundant "|" character but still failed. I've read some similar questions but they are written in Java so I can't understand. Could somebody show me how to do it?
Here is my code which contains the test case above:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* get_node(int value) {
struct Node* new = (struct Node*) malloc(sizeof (struct Node));
new->data = value;
new->left = NULL;
new->right = NULL;
return new;
}
void insert(struct Node **ptr, int value) {
struct Node* root = *ptr;
if(root == NULL) {
*ptr = get_node(value);
} else if(value <= root->data){
insert(&root->left, value);
} else {
insert(&root->right, value);
}
}
void print_subtree(struct Node* root, int indent, int is_right) {
if(root == NULL)
return;
printf("\n");
for (int i = 0; i < indent; ++i) {
printf("| ");
}
if(is_right)
printf("└─%d", root->data);
else
printf("├─%d", root->data);
print_subtree(root->left, indent + 1, 0);
print_subtree(root->right, indent + 1, 1);
}
void print(struct Node* root) {
if(root != NULL) {
printf("%d", root->data);
print_subtree(root->left, 0, 0);
print_subtree(root->right, 0, 1);
}
}
int main() {
struct Node* root = NULL;
insert(&root, 50);
insert(&root, 25);
insert(&root, 75);
insert(&root, 10);
insert(&root, 40);
insert(&root, 60);
insert(&root, 90);
insert(&root, 5);
insert(&root, 15);
insert(&root, 35);
insert(&root, 45);
insert(&root, 55);
insert(&root, 65);
insert(&root, 85);
insert(&root, 95);
print(root);
}