FunctionRacerProblemsRace

Closest to Everyone

HardTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. The distance between two nodes is the number of links on the way from one to the other, going up and down as needed.

For a node, add up its distances to all the other nodes. Return the smallest total that any node has. The values in the nodes do not matter.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [1,2,3,4,5]
returns 5

From the node 2 the totals are 1 to its parent, 1 to each of its children and 2 to the node 3: 5. From the root it would be 6.

Example 2

root [1,null,2,null,3,null,4,null,5]
returns 6

The middle node of the chain has two nodes at distance 1 and two at distance 2.

Example 3

root [1]
returns 0

There are no other nodes.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems