1. Shared best
A closure variable tracks the longest path seen.
let diameter = 0Typorithm · medium
Step 1 of 8 · intro card
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.
Path through a node = left + right heights.
Return height, track diameter separately.
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;
}Connect each part of the code to the concept before you type.
A closure variable tracks the longest path seen.
let diameter = 0Compute each child's height first.
const left = depth(node.left)The longest path bending at this node spans both subtrees.
diameter = Math.max(diameter, left + right)Upward, the node reports its own height, not the diameter.
return 1 + Math.max(left, right)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.