Diameter of a Binary Tree | A binary tree Node ; utility class to pass height object ; Optimised recursive function to find diameter of binary tree ; to store height of left and right subtree ; base condition - when binary tree is empty ; diameter is also 0 ; ldiameter -- > diameter of left subtree rdiamter -- > diameter of right subtree height of left subtree and right subtree is obtained from lh and rh and returned value of function is stored in ldiameter and rdiameter ; height of tree will be max of left subtree height and right subtree height plus1 ; function to calculate diameter of binary tree ; Constructed binary tree is 1 / \ 2 3 / \ 4 5 ; Function Call
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT class Height : NEW_LINE INDENT def __init ( self ) : NEW_LINE INDENT self . h = 0 NEW_LINE DEDENT DEDENT def diameterOpt ( root , height ) : NEW_LINE INDENT lh = Height ( ) NEW_LINE rh = Height ( ) NEW_LINE if root is None : NEW_LINE INDENT height . h = 0 NEW_LINE return 0 NEW_LINE DEDENT ldiameter = diameterOpt ( root . left , lh ) NEW_LINE rdiameter = diameterOpt ( root . right , rh ) NEW_LINE height . h = max ( lh . h , rh . h ) + 1 NEW_LINE return max ( lh . h + rh . h + 1 , max ( ldiameter , rdiameter ) ) NEW_LINE DEDENT def diameter ( root ) : NEW_LINE INDENT height = Height ( ) NEW_LINE return diameterOpt ( root , height ) NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print ( diameter ( root ) ) NEW_LINE