Longest Univalue Path (LeetCode 687): Solution and Explanation

Medium
Tree
Depth First Search
Binary Tree

Given a binary tree, return the number of edges on the longest path whose nodes all share one value. The path can start and end anywhere.

Intuition

Any path in a tree has one highest node. From there it goes down into the left subtree, down into the right subtree, or both. Call that highest node the bend.

If every node knew how far a chain of its own value reaches straight down, the best path bending at that node would be the left chain plus the right chain.

A child's chain only helps its parent when the child has the same value. A different value cuts the chain to 0. And a node can pass only one of its two chains up, because a path cannot fork.

Approach: Post-order arms

  1. Keep a global best = 0.
  2. arm(node) returns 0 for null. Otherwise it first computes arm(left) and arm(right).
  3. If the left child exists and has the same value, left = arm(left) + 1, else left = 0. Same for the right side.
  4. Update best = max(best, left + right): that is the path bending at this node.
  5. Return max(left, right) to the parent and finally return best.

Step-by-step example

root = [5,4,5,1,1,null,5]
  1. The leaves 1, 1 and the lower 5 return 0.
  2. Node 4: both children are 1, which differ, so both arms are 0. best stays 0.
  3. Right node 5: its right child 5 matches, so right arm = 0 + 1 = 1. best = 1. It returns 1.
  4. Root 5: left child 4 differs (arm 0), right child 5 matches (arm 1 + 1 = 2). best = 0 + 2 = 2.
  5. Return 2.

Code: Python, Java, C++

1class Solution:
2    def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
3        self.best = 0
4        def arm(node):
5            if not node:
6                return 0
7            left = arm(node.left)
8            right = arm(node.right)
9            left = left + 1 if node.left and node.left.val == node.val else 0
10            right = right + 1 if node.right and node.right.val == node.val else 0
11            self.best = max(self.best, left + right)
12            return max(left, right)
13        arm(root)
14        return self.best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is visited once and does constant work.

Space

O(h)

The recursion stack grows with the height of the tree.

Other approaches

Start a search at every node (time O(n^2), space O(h))

For each node, measure the longest same-value chains below it with a fresh DFS. Correct but repeats work.

Iterative post-order (time O(n), space O(n))

Use an explicit stack and a map from node to arm length. Same idea without recursion, useful for very deep trees.

Common mistakes

  • Counting nodes instead of edges. A single node is a path of length 0.
  • Returning left + right to the parent. A path cannot fork, so only the longer arm can continue upward.
  • Passing the child's arm up even when the child's value differs. A different value resets that side to 0.

Frequently asked questions

Why do we need a global best instead of just returning a value?

The value returned to the parent is a one-sided arm, but the best path may bend at a lower node and use both sides. The global keeps that two-sided answer.

Does the path have to go through the root?

No. Every node gets a turn as the bend point, so paths deep in the tree are found too.

What about an empty tree?

The answer is 0, since there are no edges at all.