Print the height of binary tree separately

Viewed 209
int height(struct node* node) 
{ 
    /* base case tree is empty */
    if (node == NULL) 
        return 0; 
  
    /* If tree is not empty then height = 1 + max of left 
      height and right heights */
    return 1 + max(height(node->left), height(node->right)); 
}

Above is very basic code to find the height of binary Tree. But I am not able to print the left and right height separately in the calling function . I tried by passing the call by reference too, but I got unexpected results.

Problem Statement: find the height of binary search tree where a tree with 1 node will be considered as height 0, and a tree with no node will be considered as height -1.

Expected Output: left height :1, right height: 3 (Cat is the root node)

          cat
         /    \
      bear     dog
     /         /   \
 alligator   dear   tiger
             /       /
            cow    lion
                   /
                 horse

This code has to be written in the C language. Is this method correct to find the height?

Following output generated to cross verify tree by inorder traversal

 node:alligator 
 node:bear   bear:->left  alligator
 node:cat    cat:->left  bear     cat:->right dog
 node:cow 
 node:deer   deer:->left  cow
 node:dog    dog:->left  deer     dog:->right tiger
 horse 
 lion   lion:->left  horse
 tiger      tiger:->left  lion
3 Answers

If you want the left and right height separately, find it out separately:

int  left_height = height( root->left) - 1;
int right_height = height(root->right) - 1;

Calling printf("%d", height(root->left)) and printf("%d", height(root->right)) on your root node should do the job.

Write a wrapper function for your height function:

void printHeight(struct node* root)
{
    int leftHeight = (root==nullptr) ? 0 : height(root->left);
    int rightHeight = (root==nullptr) ? 0 : height(root->right);

    printf("left height: %d, right height: %d", leftHeight-1, rightHeight-1);
}
Related