Ctrl K

Equal-Label Tree Path

Medium
You are given the root of a binary tree; every node holds an integer label. Find the longest path in the tree whose nodes all carry the same label. The path may start and end at any nodes and does not have to pass through the root; it uses each edge at most once. Return the length of that path, measured in edges. If the tree is empty, return 0.
Example 1
root=tree_node([7, 7, 7, 7, None, 2, 7]) → 4

The path runs from the left grandchild 7 up through the left child and the root, then down the right child to its right child: five nodes labelled 7, four edges.

Example 2
root=tree_node([3, 1, 2]) → 0

All labels differ, so the path is a single node with no edges.

Example 3
root=tree_node([]) → 0

An empty tree has no paths, so the answer is 0.

Constraints
  • 0 ≤ number of nodes ≤ 10⁵
  • The depth of the tree is at most 1000
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumDigit Branch Totals Medium
loading Python…
Input
root=tree_node([7, 7, 7, 7, None, 2, 7])
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 109 tests on the server, hidden ones included.