Diameter of a Binary Tree using Top Down Recursion
Last Updated : 24 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Given a binary tree, the task is to determine the diameter of the tree. The diameter/width of a tree is defined as the number of edges on the longest path between any two nodes.
Examples:
Input:
Output: 2 Explanation: The longest path has 2 edges (node 2 -> node 1 -> node 3).
The idea is to recursively traverse the tree using Preorder traversal. For each node, find the height of left subtree and right subtree and compare the diameter (sum of height of left subtree + height of right subtree) with the maximum diameter.
C++
// C++ program to find the diameter// of a binary tree.#include<iostream>#include<algorithm>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to compute the height of a tree.intheight(Node*root){// Base case: tree is emptyif(root==nullptr)return0;// If tree is not empty then height = 1 +// max of left height and right heightsreturn1+max(height(root->left),height(root->right));}// Function to get diameter of a binary treeintdiameter(Node*root){if(root==nullptr)return0;// Get the height of left and right// sub-treesintlheight=height(root->left);intrheight=height(root->right);// Get the diameter of left and right// sub-treesintldiameter=diameter(root->left);intrdiameter=diameter(root->right);// Return max of the following three:// 1) Diameter of left subtree// 2) Diameter of right subtree// 3) Height of left subtree + height of right subtreereturnmax({lheight+rheight,ldiameter,rdiameter});}intmain(){// Constructed binary tree is// 5// / \ // 8 6// / \ /// 3 7 9Node*root=newNode(5);root->left=newNode(8);root->right=newNode(6);root->left->left=newNode(3);root->left->right=newNode(7);root->right->left=newNode(9);cout<<diameter(root)<<endl;return0;}
C
// C program to find the diameter// of a binary tree.#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Function to compute the height of a tree.intheight(structNode*root){// Base case: tree is emptyif(root==NULL)return0;// If tree is not empty then height = 1 +// max of left height and right heightsintleftHeight=height(root->left);intrightHeight=height(root->right);return1+(leftHeight>rightHeight?leftHeight:rightHeight);}// Function to get diameter of a binary treeintdiameter(structNode*root){if(root==NULL)return0;// Get the height of left and right sub-treesintlheight=height(root->left);intrheight=height(root->right);// Get the diameter of left and right sub-treesintldiameter=diameter(root->left);intrdiameter=diameter(root->right);// Diameter of current subtree intcurr=lheight+rheight;// Return max of the following three:// 1) Diameter of left subtree// 2) Diameter of right subtree// 3) Height of left subtree + height of right subtreeif(ldiameter>rdiameter&&ldiameter>curr)returnldiameter;elseif(rdiameter>ldiameter&&rdiameter>curr)returnrdiameter;returncurr;}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=NULL;newNode->right=NULL;returnnewNode;}intmain(){// Constructed binary tree is// 5// / \ // 8 6// / \ /// 3 7 9structNode*root=createNode(5);root->left=createNode(8);root->right=createNode(6);root->left->left=createNode(3);root->left->right=createNode(7);root->right->left=createNode(9);printf("%d\n",diameter(root));return0;}
Java
// Java program to find the diameter// of a binary tree.importjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function to compute the height of a tree.staticintheight(Noderoot){// Base case: tree is emptyif(root==null)return0;// If tree is not empty then height = 1 +// max of left height and right heightsreturn1+Math.max(height(root.left),height(root.right));}// Function to get diameter of a binary treestaticintdiameter(Noderoot){if(root==null)return0;// Get the height of left and right sub-treesintlheight=height(root.left);intrheight=height(root.right);// Get the diameter of left and right sub-treesintldiameter=diameter(root.left);intrdiameter=diameter(root.right);// Return max of the following three:// 1) Diameter of left subtree// 2) Diameter of right subtree// 3) Height of left subtree + height// of right subtreereturnMath.max(lheight+rheight,Math.max(ldiameter,rdiameter));}publicstaticvoidmain(String[]args){// Constructed binary tree is// 5// / \// 8 6// / \ /// 3 7 9Noderoot=newNode(5);root.left=newNode(8);root.right=newNode(6);root.left.left=newNode(3);root.left.right=newNode(7);root.right.left=newNode(9);System.out.println(diameter(root));}}
Python
# Python program to find the diameter# of a binary tree.classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to compute the height # of a tree.defheight(root):# Base case: tree is emptyifrootisNone:return0# If tree is not empty then height = 1 +# max of left height and right heightsreturn1+max(height(root.left),height(root.right))# Function to get diameter of a binary treedefdiameter(root):ifrootisNone:return0# Get the height of left and # right sub-treeslheight=height(root.left)rheight=height(root.right)# Get the diameter of left and # right sub-treesldiameter=diameter(root.left)rdiameter=diameter(root.right)# Return max of the following three:# 1) Diameter of left subtree# 2) Diameter of right subtree# 3) Height of left subtree + height of right subtreereturnmax(lheight+rheight,ldiameter,rdiameter)if__name__=="__main__":# Constructed binary tree is# 5# / \# 8 6# / \ /# 3 7 9root=Node(5)root.left=Node(8)root.right=Node(6)root.left.left=Node(3)root.left.right=Node(7)root.right.left=Node(9)print(diameter(root))
C#
// C# program to find the diameter// of a binary tree.usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to compute the // height of a tree.staticintheight(Noderoot){// Base case: tree is emptyif(root==null)return0;// If tree is not empty then height = 1 +// max of left height and right heightsreturn1+Math.Max(height(root.left),height(root.right));}// Function to get diameter of// a binary treestaticintdiameter(Noderoot){if(root==null)return0;// Get the height of left and // right sub-treesintlheight=height(root.left);intrheight=height(root.right);// Get the diameter of left and right sub-treesintldiameter=diameter(root.left);intrdiameter=diameter(root.right);// Return max of the following three:// 1) Diameter of left subtree// 2) Diameter of right subtree// 3) Height of left subtree + height of right subtreereturnMath.Max(lheight+rheight,Math.Max(ldiameter,rdiameter));}staticvoidMain(string[]args){// Constructed binary tree is// 5// / \// 8 6// / \ /// 3 7 9Noderoot=newNode(5);root.left=newNode(8);root.right=newNode(6);root.left.left=newNode(3);root.left.right=newNode(7);root.right.left=newNode(9);Console.WriteLine(diameter(root));}}
JavaScript
// JavaScript program to find the diameter// of a binary tree.classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to compute the height of a tree.functionheight(root){// Base case: tree is emptyif(root===null)return0;// If tree is not empty then height = 1 +// max of left height and right heightsreturn1+Math.max(height(root.left),height(root.right));}// Function to get diameter of a binary treefunctiondiameter(root){if(root===null)return0;// Get the height of left and right sub-treesconstlheight=height(root.left);constrheight=height(root.right);// Get the diameter of left and right sub-treesconstldiameter=diameter(root.left);constrdiameter=diameter(root.right);// Return max of the following three:// 1) Diameter of left subtree// 2) Diameter of right subtree// 3) Height of left subtree + height of right subtreereturnMath.max(lheight+rheight,ldiameter,rdiameter);}// Driver Code// Constructed binary tree is// 5// / \// 8 6// / \ /// 3 7 9letroot=newNode(5);root.left=newNode(8);root.right=newNode(6);root.left.left=newNode(3);root.left.right=newNode(7);root.right.left=newNode(9);console.log(diameter(root));
Output
4
Time Complexity: O(n^2), where n is the number of nodes in tree. Auxiliary Space: O(h) due to recursive calls.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.