2
I need to adjust this code so that the tree is printed with margin indentation proportional to the node depth, and that it prints a character ' - ' to represent each NULL
. Anyone can help?
If I have not explained right and someone wants to see what the question asks, is on this link, exercises 3, question 3: https://www.ime.usp.br/~pf/algorithms/classes/bint.html
This is the statement of the exercise:
3. Write a function that prints the contents of each node of a binary tree with margin indentation proportional to the depth of the node. Follow an example of a tree and its representation (the characters
'-'
representNULL
):555 555 / \ 333 111 333 888 - / \ \ - 111 444 999 444 - - 888 - 999 - -
Just follow my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct noh{
int valor;
struct noh *esquerda;
struct noh *direita;
}no;
void desenha(no *arvore, int depth, char *path, int dir){
int i, j;
if (arvore == NULL)
return;
depth++;
desenha(arvore->direita, depth, path, 1);
path[depth-2] = 0;
if(dir)
path[depth-2] = 1;
if(arvore->esquerda)
path[depth-1] = 1;
for(i=0; i<depth-1; i++){
if(i == depth-2)
printf(" ");
else if(path[i])
printf(" ");
else
printf(" ");
for(j=1; j<depth; j++)
if(i < depth-2)
printf(" ");
else
printf(" ");
}
printf("%d\n", arvore->valor);
for(i=0; i<depth; i++){
if(path[i])
printf(" ");
else
printf(" ");
for(j=1; j<depth; j++)
printf(" ");
}
desenha(arvore->esquerda, depth, path, 0);
}
void arvbin(no *arvore){
char path[255] = {};
desenha(arvore, 0, path, 0);
}
no n1, n2, n3, n4, n5, n6;
int main(){
n1.valor = 444;
n2.valor = 333;
n3.valor = 999;
n4.valor = 555;
n5.valor = 111;
n6.valor = 888;
n1.direita = &n2;
n1.esquerda = &n3;
n2.direita = &n4;
n2.esquerda = &n5;
n3.direita = &n6;
arvbin(&n1);
return 0;
}