Height of the Tree.

 Below is the source code of checking the height of the binary tree.

If you need any explanation then please feel free to contact me on my email i.e harshprasadaju@gmail.com.

Thankyou.

#include <stdio.h>
#include <stdlib.h>
struct tree
{
    int data;
    struct tree *left;
    struct tree *right;
};
struct tree *Createnode(int data)
{
    struct tree *nd = (struct tree *)malloc(sizeof(struct tree));
    nd->left = NULL;
    nd->right = NULL;
    nd->data = data;
    return nd;
}
void inOrderTraversal(struct tree *root)
{
    if (root != NULL)
    {
        inOrderTraversal(root->left);
        printf("%d "root->data);
        inOrderTraversal(root->right);
    }
}
int heightOfTree(struct tree *root)
{
    if (root)
    {
        if (root->left == NULL && root->right == NULL)
            return 0;
        else
            return 1 + (heightOfTree(root->left>= heightOfTree(root->right? heightOfTree(root->left: heightOfTree(root->right));
    }
    else
    return 0;
}

int main()
{
    struct tree *t = Createnode(4);
    struct tree *t1 = Createnode(1);
    struct tree *t2 = Createnode(6);
    struct tree *t4 = Createnode(5);
    struct tree *t5 = Createnode(2);
    struct tree *t6 = Createnode(8);
    struct tree *t7 = Createnode(9);
    struct tree *t8 = Createnode(10);
    struct tree *t9 = Createnode(12);
    t->left = t1;
    t->right = t2;
    t1->left = t4;
    t1->right = t6;
    t2->right = t5;
    t2->left = t7;
    t5->right = t8;
    t8->left = t9;
    printf("Height of thr tree is : %d"heightOfTree(t));

    return 0;
}


Comments

Popular posts from this blog

Insert and delete item in a BST

Multiple parenthesis balancing problem using stacks