Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is defined as the length of the longest path between any two nodes in the tree. The path may or may not pass through the root.
The length of a path between two nodes is measured as the number of edges between them.
The longest path between any two nodes in a binary tree is determined by its height properties. The key observations are:
To compute the diameter efficiently, we use a recursive depth-first search (DFS) approach with the following steps:
(leftHeight + rightHeight)
.1 + max(leftHeight, rightHeight)
.This approach ensures we efficiently compute the diameter in O(N) time complexity, where N is the number of nodes.
1
/ \
2 3
/ \
4 5
1
, and node 5 = 1
.1 + max(1, 1) = 2
.1
.1 (left) + 1 (right) = 2
.2 (left) + 1 (right) = 3
.3
(Valid paths: [4 → 2 → 1 → 3]
or [5 → 2 → 1 → 3]
)
public class DiameterOfBinaryTree {
static int maxDiameter = 0;
public static int height(TreeNode root) {
if (root == null) return 0;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
// Update the maximum diameter found
maxDiameter = Math.max(maxDiameter, leftHeight + rightHeight);
// Return height of current node
return 1 + Math.max(leftHeight, rightHeight);
}
public static int diameterOfBinaryTree(TreeNode root) {
maxDiameter = 0;
height(root);
return maxDiameter;
}
height(root)
performs O(1) operations per node, leading to an O(N) total runtime.H = log N
, so space complexity is O(log N).H = N
, so worst-case space complexity is O(N).Our Program make you Job Ready for your Dream Company 🚀