Longest Univalue Path

35 min · longestUnivaluePath()

Matching values can form a road that bends through a parent: one arm arrives from the left, the other leaves through the right.

You're given the root of a binary tree. A univalue path is a path where every node holds the same value. Return the greatest number of edges on any such path.

A few ground rules:

  • The path may start and end at any nodes.
  • It may join a left arm and a right arm through one node.
  • Count edges, not nodes.
  • An empty tree and a single-node tree both return 0.
  • Equal values elsewhere in the tree don't help unless equal-valued edges connect them.

Constraints

  • 0 <= node count <= 10_000
  • -1_000 <= node.val <= 1_000

Hints

Choose a meeting node

At each node, ask how far an equal-valued path can extend down the left and down the right. If both arms match the node, they can be joined.

One arm travels upward

A post-order traversal handles both children before their parent. The path through a node may use both arms, but its parent can continue through only one of them. Return the longer arm upward and keep the joined length in a global best.

Break on a changed value

A child's stored arm counts only when child.val == node.val. Otherwise that side contributes 0, even if a longer matching path exists deeper in the child subtree.

Follow-up

Could you recover the two endpoint nodes of the longest matching path as well as its length?

Visible cases

Examples

Example 1

ready
Input
root = [
  5,
  4,
  5,
  1,
  1,
  5
]
Expected
2
Why
three connected 5s form a two-edge path

Example 2

ready
Input
root = [
  1,
  4,
  5,
  4,
  4,
  5
]
Expected
2
Why
the best path joins the two 4-valued children

Example 3

ready
Input
root = [
  1
]
Expected
0
Why
one node contains no edge

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite