Typorithm · medium

Diameter of Binary Tree

diameter-of-binary-treetreesdfsglobal-stateheight
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Diameter of Binary Tree

0%

Trees

DFS returns each node's height while a closure tracks the longest left+right path bending at any node.

The diameter is the longest path between any two nodes, which may not pass through the root.

At each node, the path that bends there has length left height + right height.

The recursion returns height upward, but a shared variable records the best bend seen anywhere.

01

Path through a node = left + right heights.

02

Return height, track diameter separately.

03

The answer counts edges, not nodes.

function diameterOfBinaryTree(root) {
  let diameter = 0;

  function depth(node) {
    if (node === null) {
      return 0;
    }
    const left = depth(node.left);
    const right = depth(node.right);
    diameter = Math.max(diameter, left + right);
    return 1 + Math.max(left, right);
  }

  depth(root);
  return diameter;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Shared best

A closure variable tracks the longest path seen.

let diameter = 0

2. Subtree heights

Compute each child's height first.

const left = depth(node.left)

3. Path through node

The longest path bending at this node spans both subtrees.

diameter = Math.max(diameter, left + right)

4. Return height

Upward, the node reports its own height, not the diameter.

return 1 + Math.max(left, right)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Diameter of Binary Tree: Lesson & Practice · Typorithm | ApplyDjinn