1
Let T be a binary tree with n positions, and, for any position p in T , let d p denote the depth of p in T . The distance between two positions, p and q in T is d p +d q -2d a , where a is the lowest common ancestor (LCA) of p and q . The diameter of T is the maximum distance between two positions in T . Describe an efficient algorithm for finding the diameter of T . What is the running time of your algorithm? In Java. Solution: Algorithm to find Diameter of binary tree: If binary tree t is EMPTY then return zero Get the height of left and right sub-trees Get the diameter of left and right sub-trees Return max of o Diameter of Left Max path o Diameter of right Max path o Height of left Max path + height of right Max path + 1 Running time of algorithm is O(n). The position p of the binary tree t compared n times to find the maximum distance between positions in a binary tree t. Hence the total running time of the algorithm is O(n).

7063049

  • Upload
    vkthik

  • View
    212

  • Download
    0

Embed Size (px)

DESCRIPTION

Diameter of binary tree

Citation preview

Page 1: 7063049

Let T be a binary tree with n positions, and, for any position p in T, let dp denote the depth of p in T. The distance between two positions, p and q in T is dp+dq-2da, where a is the lowest common ancestor (LCA) of p and q. The diameter of T is the maximum distance between two positions in T. Describe an efficient algorithm for finding the diameter of T. What is the running time of your algorithm? In Java.

Solution:

Algorithm to find Diameter of binary tree:

If binary tree t is EMPTY then return zero Get the height of left and right sub-trees Get the diameter of left and right sub-trees Return max of

o Diameter of Left Max path o Diameter of right Max patho Height of left Max path + height of right Max path +

1Running time of algorithm is O(n).

The position p of the binary tree t compared n times to find the maximum distance between positions in a binary tree t.

Hence the total running time of the algorithm is O(n).