Find height of a binary tree

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

struct node
{
    int data;
    struct node * left;
    struct node * right;
};

// Height of Tree
int maxDepth(struct node * root)
{
   int depth      = 0;
   int leftdepth  = 0;
   int rightdepth = 0;
  
   if(root == NULL)
     return 0;
  
   leftdepth  = maxDepth(root->left);;
   rightdepth = maxDepth(root->right);
  
   depth = (leftdepth>rightdepth) ? (leftdepth+1): (rightdepth+1);

   return depth;
}

struct node* newNode(int value)
{
    struct node* node = (struct node *)malloc(sizeof(struct node));

    node->data   = value;
    node->left   = NULL;
    node->right  = NULL;

    return node;
}

int main(void)
{
    struct node *root = newNode(1);
    root->left        = newNode(2);
    root->right       = newNode(3);
    root->left->left  = newNode(2);
    root->left->right = newNode(3);
   
    printf("Height of tree is %d \n", maxDepth(root));
   
    return 0;
}


No comments:

Post a Comment