// Its basically the longest path between 2 nodes in a tree
// This solution give O(n) time complexity
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node * left;
struct node * right;
};
int max(int a, int b)
{
return (a > b)? a: b;
}
// Diameter of a tree
int diameter(struct node *tree, int *height)
{
int lheight = 0;
int rheight = 0;
int ldiameter = 0;
int rdiameter = 0;
if(tree == NULL)
{
*height = 0;
return 0;
}
ldiameter = diameter(tree->left, &lheight);
rdiameter = diameter(tree->right, &rheight);
*height = max(lheight, rheight) + 1;
return max(lheight+rheight+1, max(ldiameter, rdiameter));
}
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)
{
int height = 0;
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", diameter(root, &height));
return 0;
}
Find diameter of a binary tree - O(n) time complexity
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment