Skip to main content

Diameter of Binary Tree

LeetCode 543 | Difficulty: Easy​

Easy

Problem Description​

Given the root of a binary tree, return the length of the diameter of the tree.

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

The length of a path between two nodes is represented by the number of edges between them.

Example 1:

Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].

Example 2:

Input: root = [1,2]
Output: 1

Constraints:

- The number of nodes in the tree is in the range `[1, 10^4]`.

- `-100 <= Node.val <= 100`

Topics: Tree, Depth-First Search, Binary Tree


Approach​

Tree DFS​

Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β†’ go right β†’ combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.

When to use

Path problems, subtree properties, tree structure manipulation.


Solutions​

Solution 1: C# (Best: 120 ms)​

MetricValue
Runtime120 ms
MemoryN/A
Date2018-04-25
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int DiameterOfBinaryTree(TreeNode root) {
if(root==null) return 0;
int left = DiameterOfBinaryTree(root.left);
int right = DiameterOfBinaryTree(root.right);
int cur = Depth(root.left) + Depth(root.right);
return Math.Max(cur, Math.Max(left, right));

}

public int Depth(TreeNode root){
if(root==null) return 0;
else return 1 + Math.Max(Depth(root.left), Depth(root.right));
}
}

Complexity Analysis​

ApproachTimeSpace
Tree Traversal$O(n)$$O(h)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Consider: "What information do I need from each subtree?" β€” this defines your recursive return value.