Diameter of a Binary Tree | Class containing left and right child of current node and key value ; Class to print the Diameter ; The function Compute the " height " of a tree . Height is the number of nodes along the longest path from the root node down to the farthest leaf node . ; base case tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Function to get diameter of a binary tree ; base case where tree is empty ; get the height of left and right sub - trees ; get the diameter of left and right sub - trees ; 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 ; A wrapper over diameter ( Node root ) ; Driver Code ; creating a binary tree and entering the nodes ; Function Call
using System ; namespace Tree { class Tree < T > { public Tree ( T value ) { this . value = value ; } public T value { get ; set ; } public Tree < T > left { get ; set ; } public Tree < T > right { get ; set ; } } public class TreeDiameter { Tree < int > root ; int Height ( Tree < int > node ) { if ( node == null ) return 0 ; return 1 + Math . Max ( Height ( node . left ) , Height ( node . right ) ) ; } int Diameter ( Tree < int > root ) { if ( root == null ) return 0 ; int lHeight = Height ( root . left ) ; int rHeight = Height ( root . right ) ; int lDiameter = Diameter ( root . left ) ; int rDiameter = Diameter ( root . right ) ; return Math . Max ( lHeight + rHeight + 1 , Math . Max ( lDiameter , rDiameter ) ) ; } int Diameter ( ) { return Diameter ( root ) ; } public static void Main ( string [ ] args ) { TreeDiameter tree = new TreeDiameter ( ) ; tree . root = new Tree < int > ( 1 ) ; tree . root . left = new Tree < int > ( 2 ) ; tree . root . right = new Tree < int > ( 3 ) ; tree . root . left . left = new Tree < int > ( 4 ) ; tree . root . left . right = new Tree < int > ( 5 ) ; Console . WriteLine ( $" The diameter of given binary tree is :  { tree . Diameter ( ) } " ) ; } } }