You get the root of a binary tree. Look for a path between two nodes along the tree's edges where every node on the path holds the same value. The path does not have to pass through the root, and it may go up from one node and back down to another.
Return the length of the longest such path, counted in edges. A single node is a path of length 0, and an empty tree gives 0.
Example 1
Input: root = [3, 6, 6, 6, 6, null, 3] Output: 2 Why: 6 → 6 → 6 bends at the root's left child
2 more examples and the constraints
Example 2
Input: root = [2, 2, 2, 2, null, null, 2] Output: 4 Why: five 2s in a row, through the root
Example 3
Input: root = [4, 9, 8] Output: 0 Why: no edge joins two equal values
Constraints
- 0 ≤ number of nodes ≤ 10,000
- −1,000 ≤ Node.val ≤ 1,000
- The tree is at most 1,000 levels deep
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Measure from every nodeO(n·h)
- One post-order passO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 1,000-deep chain of equal values | Verdict |
|---|---|---|---|
| Measure from every node | O(n·h) | Re-measures the same chains | |
| One post-order pass | O(n) | Best; each node once |
n = number of nodes, h = height of the tree.
Edge cases to test
- Empty tree. root is null: return 0.
- Single node. [8] has no edges, so 0.
- No equal neighbours. [4, 9, 8] gives 0, not 1.
- Path bends below the root. Example 1: the best path never touches the root.
- Long straight chain. 1,000 equal nodes in a line give 999 edges.
Common mistakes
- Counting nodes instead of edges, which is off by one.
- Returning left + right to the parent, which lets a path fork into three branches.
- Keeping a child's arm when its value differs; the arm must reset to 0 there.
How to talk through it
- 1Clarify. Is length counted in edges or nodes? Can the path skip the root? What does an empty tree return?
- 2Name the shape. Every path has a top node where it bends; its two sides are straight chains going down.
- 3Give the brute force. Try every node as the top and measure both chains fresh: O(n·h).
- 4Share the work. One post-order pass returns the longer chain and records left + right at each node.
- 5Test out loud. Run an empty tree, a single node, Example 1 where the path skips the root, and a long chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?