FunctionRacerProblemsRace

Longest Same-Value Path

MediumTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. Find the longest path in the tree (it may start and end at any nodes, and may turn at a node by going down both sides) in which every node has the same value. Return its length counted in edges. A tree with no two connected equal values gives 0.

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 [5,4,5,1,1,null,5]
returns 2

The two 5s under the root connect through the root: 2 edges.

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