Diameter of a Binary Tree using Top Down Recursion
Last Updated : 24 Jan, 2025
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.
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.
Output
4
Time Complexity: O(n^2), where n is the number of nodes in tree. Auxiliary Space: O(h) due to recursive calls.