Question: Given a binary tree, write a program to find maximum distance between any two nodes of the tree.
Time Complexity: O(n)
Time Complexity: O(n)
int
diameter(tree *t)
{
/* left diamter, right diameter, node diameter */
int ld, rd, nd;
if (!t) {
return 0;
}
ld = diameter(t->left);
rd = diameter(t->right);
nd = height(t->left) + height(t->right) + 1;
return max3(ld, rd, nd);
}
Slightly more efficient algorithm, this calculates the height of the tree along with diameter.
int
diameter2(tree *t, int *height)
{
/* left diameter, right diameter, node diameter */
int ld, rd, nd;
/* left height, right height */
int lh, rh;
if (!t) {
*height = 0;
return 0;
}
ld = diameter2(t->left, &lh);
rd = diameter2(t->right, &rh);
nd = lh + rh + 1;
*height = max(lh, rh) + 1;
return max3(ld, rd, nd);
}
max3 - returns maximum of the three arguments
{
/* left diamter, right diameter, node diameter */
int ld, rd, nd;
if (!t) {
return 0;
}
ld = diameter(t->left);
rd = diameter(t->right);
nd = height(t->left) + height(t->right) + 1;
return max3(ld, rd, nd);
}
Slightly more efficient algorithm, this calculates the height of the tree along with diameter.
int
diameter2(tree *t, int *height)
{
/* left diameter, right diameter, node diameter */
int ld, rd, nd;
/* left height, right height */
int lh, rh;
if (!t) {
*height = 0;
return 0;
}
ld = diameter2(t->left, &lh);
rd = diameter2(t->right, &rh);
nd = lh + rh + 1;
*height = max(lh, rh) + 1;
return max3(ld, rd, nd);
}
max3 - returns maximum of the three arguments
No comments:
Post a Comment