Diameter of a Binary Tree | Recursive optimized C ++ program to find the diameter of a Binary Tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; define height = 0 globally and call diameterOpt ( root , height ) from main ; lh -- > Height of left subtree rh -- > Height of right subtree ; ldiameter -- > diameter of left subtree rdiameter -- > Diameter of right subtree ; base condition - when binary tree is empty ; diameter is also 0 ; Get the heights of left and right subtrees in lh and rh And store the returned values in ldiameter and ldiameter ; Height of current node is max of heights of left and right subtrees plus 1 ; Driver Code ; Constructed binary tree is 1 / \ 2 3 / \ 4 5 ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int diameterOpt ( struct node * root , int * height ) { int lh = 0 , rh = 0 ; int ldiameter = 0 , rdiameter = 0 ; if ( root == NULL ) { * height = 0 ; return 0 ; } ldiameter = diameterOpt ( root -> left , & lh ) ; rdiameter = diameterOpt ( root -> right , & rh ) ; * height = max ( lh , rh ) + 1 ; return max ( lh + rh + 1 , max ( ldiameter , rdiameter ) ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; int height = 0 ; cout << " Diameter ▁ of ▁ the ▁ given ▁ binary ▁ tree ▁ is ▁ " << diameterOpt ( root , & height ) ; return 0 ; }