How to "draw" a binary tree?

0

I have a problem trying to create an algorithm to "draw" a binary tree as below:

But I have a problem to implement. I'll show my code below:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


typedef struct {
    int data;
    struct Node *left;
    struct Node * right;
} Node;
Node* newNode(int data) {
        Node* node = malloc(sizeof (Node));
        node->data = data;
        node->left = NULL;
        node->right = NULL;
        return node;
};
Node* insert(Node* node, int data) {
    if (node == NULL){
        return(newNode(data));  
    }
    if (data <= node->data){
        node->left = insert(node->left, data);
    }else{
        node->right = insert(node->right, data);
    }
    return node; 
}; 
int lookup(Node* node, int target) {
    if (node == NULL) {
        return 0; 
    }
    if (target == node->data){
        return 1; 
    }
    if (target < node->data) {
        return(lookup(node->left, target));
    }
    return(lookup(node->right, target));

}; 
int altura (Node* node){
    if (node == NULL) 
        return 0; 

    int lDepth = altura(node->left); 
    int rDepth = altura(node->right);

    if (lDepth > rDepth) 
        return (lDepth + 1); 

    return (rDepth + 1); 
} 
void imprimir (Node* node, int alt, int atual){
    if (atual==0){
        return;
    }
    int s,i;    
    s = (3*(pow(2,(atual-1)))-1);
    for (i=s; i>=0; i--){
        printf(" ");
    }
    printLevel(node, alt,atual,s);
    printf("\n");
}

void printLevel(Node* node, int alt, int atual, int s){
    int i;
      if(node != NULL && alt == atual)
      {
      printf("%d",node->data);
      for (i=s; i>=0; i--){
            printf(" ");
        }
      }
      else if(node != NULL){
        printLevel(node->left,alt-1,atual, s);
        printLevel(node->right,alt-1,atual, s);
      }
    }

int main(int argc, char *argv[]) {
    int n, i ;
    Node *arvore = NULL;
    arvore = insert(arvore, 7);
    arvore = insert(arvore, 8);
    arvore = insert(arvore, 6);
    arvore = insert(arvore, 5);
    arvore = insert(arvore, 4);
    arvore = insert(arvore, 10);
    arvore = insert(arvore, 20);


    n = altura(arvore);
    //printf("%d",n);
    //printLevel(arvore,n,n);

    for (i = n; i >0 ; i--){
        imprimir(arvore,n,i);
    }

    return 0;
} 
    
asked by anonymous 06.09.2018 / 19:07

0 answers