LeetCode: Finding the Diameter of a Binary Tree

Hero image for LeetCode: Finding the Diameter of a Binary Tree.
Hero image for 'LeetCode: Finding the Diameter of a Binary Tree.'

The 'Diameter of a Binary Tree' (LeetCode #543) might sound tricky, but it's actually quite straightforward once we understand what it means. Put simply, the diameter is the longest path between two nodes in a binary tree. Knowing how to solve this problem helps us get comfortable with recursion and tree traversal and makes other treebased problems easier to tackle.

In this article, I'll do my best to clearly break down exactly what the diameter means, show you how to solve it stepbystep, and share a practical solution in JavaScript/TypeScript.


Understanding What 'Diameter' Means

Before diving into solving this problem, let's quickly clarify what the diameter of a binary tree actually is. It's the longest route between any two nodes in the tree, measured by counting the number of edges (connections between nodes). It's important to remember this route doesn't always pass through the root.

Here's a quick visual example:

      1     / \    2   3   / \  4   5

The longest path here is either 4 → 2 → 1 → 3 or 5 → 2 → 1 → 3. Both of these paths have three edges, so the diameter is 3.


Breaking the Problem down Clearly

To solve the problem, we need to consider each node as a potential central point of the longest path. For each node, we find the longest path down its left branch and the longest path down its right branch. Then, we add these two paths together. The diameter is simply the longest of these combined paths anywhere in the tree.

The neat thing is that we can find this with just one traversal of the tree if we approach it correctly.


A Practical Recursive Solution

Since trees naturally lend themselves to recursion, that's exactly what we'll use here. Let's look at a practical example in TypeScript...

TypeScript Example for the Diameter

type TreeNode = {  val: number;  left: TreeNode | null;  right: TreeNode | null;};const diameterOfBinaryTree = (root: TreeNode | null): number => {  let diameter = 0;  const findDepth = (node: TreeNode | null): number => {    if (!node) return 0;    const left = findDepth(node.left);    const right = findDepth(node.right);    diameter = Math.max(diameter, left + right);    return Math.max(left, right) + 1;  };  findDepth(root);  return diameter;};

What's Actually Happening Here?

This code might look complicated at first glance, but it's really straightforward:

  • We move through the tree from bottom to top (depthfirst search).
  • At each node, we calculate how far down we can go on the left side and on the right side.
  • We add these two lengths together to see if we've found a longer path than before.
  • Finally, we return the longest path discovered anywhere in the tree.

By doing this, we're checking every possible path once, efficiently finding the longest route.

How Efficient is This Solution?

One reason this solution works well is that we only visit each node once:

  • Time Complexity

    : O(n), each node gets visited exactly one time.
  • Space Complexity

    : O(h), with h being the tree's height, because of recursion.

This makes the solution fast and efficient, even for larger trees.


Easy Mistakes and How to Avoid Them

Here are a couple of common mistakes to keep in mind when solving this kind of problem:

Thinking Diameter Always Goes through the Root

Remember, the diameter doesn't always include the root node. Always look for paths anywhere in the tree, not just through the root.

Confusing Diameter and Height

Diameter measures the longest path between any two nodes, whilst height measures from root to leaf. It's important to have these two concepts clearly separated in your mind to avoid confusion.


Wrapping up

Finding the diameter of a binary tree is a great example of how understanding simple concepts can help us tackle seemingly tricky problems. By thinking through the problem clearly and using recursion, what initially looks complicated quickly becomes approachable. As we practise problems like this, we build confidence that makes other coding challenges feel easier, too.

Key Takeaways

  • The diameter is simply the longest path between any two nodes in a tree.
  • A single depthfirst traversal with recursion efficiently solves the problem.
  • Clearly tracking both left and right depths at each node simplifies the solution.
  • Understanding common pitfalls helps avoid easy mistakes.

With this clear understanding, treerelated problems become less intimidating and more approachable.


Categories:

  1. Algorithms
  2. Data Structures
  3. Development
  4. Guides
  5. JavaScript
  6. LeetCode