Tuesday, 30 June 2015

Diameter of Binary Tree

#include<stdio.h>


#include<stdlib.h>


struct treeNode
{
    int data;
    struct treeNode* left;
    struct treeNode* right;

};


struct treeNode* newNode(int n)
{
    struct treeNode* node = (struct treeNode*) malloc(sizeof(struct treeNode));
    node->data = n;
    node->left = NULL;
    node->right = NULL;
    return  node;

}


void printArray(int ints[], int len)
{
    int i;
    for (i = 0; i<len; i++) {
        printf("%d ", ints[i]);
    }
    printf("\n");
}

int maximum(int a, int b)
{
    return a>=b?a : b;
}

int height(struct treeNode* root)
{
    if (root == 0)
    {
        return 0;
    }

    int h = 1 + maximum(height(root->left) , height(root->right));
    return h;
}

/*
/* Return max of following three
1) Diameter of left subtree
2) Diameter of right subtree
3) Height of left subtree + height of right subtree + 1
*/

int diameter(struct treeNode* root)
{
    if (root == 0)
        return 0;
    int rHeight = height(root->right);
    int lHeight = height(root->left);

    int lDiameter = diameter(root->left);
    int rDiameter = diameter(root->right);

    return maximum(1 + rHeight + lHeight, maximum(lDiameter, rDiameter));

}




int main()
{
    /* Constructed binary tree is
    1
    /   \
    2      3
    /  \
    4     5
    */
    struct treeNode *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);

    printf("Diameter of the given binary tree is %d\n", diameter(root));

    getchar();
    return 0;
}

No comments:

Post a Comment