0

I was working on Binary Search trees and my concept on recursion is not the best that it can be. So I chose to use recursion to do all the basic tasks. The only problem that was having was with my display function. I can print out all the nodes with their respective root nodes but instead of it printing on the same line, it prints it on multiple lines. Output:

I've tried using if else statements to to call the left and right subtrees when not null but I still get the same output.

node_tree *display(node_tree *ref, int spaces){
        if (ref==NULL)
           return ref; 

        spaces = spaces/2; 
        for(int j = 0 ; j< spaces; j++)
         printf(" "); 
        printf("%d\n", ref->data);
        //display(ref->left, spaces); 
        //printf("\n");
        //printf("%d", ref->data);
        //display(ref->right, spaces);new after this line
        if (ref->left!=NULL&&ref->right!=NULL){
          display(ref->right, 3*spaces); display(ref->left, spaces);
        }   
        else if(ref->right ==NULL){
          display(ref->left, spaces);
        }
        else if(ref->left ==NULL){
          display(ref->right, 3*spaces);
        }

        //else
        //printf("%d\n", ref->data); 
    }

Output

       12
         13
   10
     11
  9

Expected Output

       12
    10    13
  9  11
  • spaces was passed from the main function with value as total nodes present in the tree. – Yathartha Oct 19 at 19:51
  • You might have to do a level order traversal for your requirement. This is working because right child does (13) not have further child. – CaffeinatedCod3r Oct 19 at 19:58
0

if left internal node have two specific external nodes and with in-order traversal; you can try it like:

<code>
int  node_height(node* node)
{
    int u, v;

    if (node == NULL)
        return -1;

    u = node_height(node->left);
    v = node_height(node->right);

    if (u > v)
        return u + 1;
    else
        return v + 1;
}

void node_print(char* ch, int height)
{
    int i;

    for (i = 0; i < height; i++)
        printf(" ");

    printf("%c", ch);
}

void node_show(node* node, int height)
{

    if (node == NULL) {
        node_print('*', node_height(node));

        return;
    }

    node_show(node->right, node_height(node) + 1);
    node_print(node->item, node_height(node));
    node_show(node->left, node_height(node) + 1);
}
</code>

call the node_show(node, node_height(node)) function with given height.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.