Longest Univalue Path

Medium

Topics
TreeDFS

Given the root of a binary tree, return the length of the longest path where every node on the path has the same value. The length is measured in edges. The path need not pass through the root.

Example 1

141555
The shaded path uses only nodes of one value, and the answer counts its edges — 2. As with the diameter, the best path through a node joins its left and right runs, but a child only extends the run when its value matches.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [5,4,5,1,1,null,5]
Output: 2

Example 2

444155
Input:  root = [1,4,5,4,4,null,5]
Output: 2

Constraints

  • 0 <= number of nodes <= 10^4
  • -1000 <= Node.val <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

A univalue path can bend at a node, running down into the left subtree and back out into the right. That means a node's contribution and what it reports to its parent are two different quantities — the same shape as the diameter-of-a-tree problem.

  • Reported upward: the longest single-sided arm of equal values starting at this node, because a parent can only extend a straight line through it.
  • Folded into the answer: the left arm plus the right arm, which is the bent path through this node.

An arm extends into a child only if the child exists and holds the same value. Both conditions are needed, and conflating them is the usual bug.

The answer is counted in edges, not nodes, so a single node scores 0 and a two-node path scores 1 — which is why each qualifying child adds exactly 1.

Approach

  1. Post-order DFS returning the longest matching arm downward.
  2. leftArm = left + 1 if the left child exists and matches, else 0; likewise right.
  3. Fold leftArm + rightArm into the running best.
  4. Return max(leftArm, rightArm).

Dry Run

tree       5
          / \
         4   5
        / \   \
       1   1   5

leaf 1 (left):   arms 0,0   best 0   returns 0
leaf 1 (right):  arms 0,0            returns 0
node 4:  children are 1 and 1, neither equals 4
         arms 0,0  -> candidate 0    returns 0
leaf 5 (bottom right): returns 0
node 5 (right child of root):
         right child is 5, matches -> rightArm = 0 + 1 = 1
         candidate 0 + 1 = 1   best 1              returns 1
root 5:  left child 4 does not match  -> leftArm 0
         right child 5 matches        -> rightArm = 1 + 1 = 2
         candidate 0 + 2 = 2   best 2              returns 2

answer 2   (the path 5 -> 5 -> 5 has two edges)

Complexity

  • Time — O(n): each node visited once.
  • Space — O(h): the recursion stack.

Common Pitfalls

  • Returning the bent length upward. A parent can only continue a straight arm, so the return value must be the one-sided maximum while the bent sum goes to the accumulator.
  • Checking the child's value without first checking the child exists, which null-dereferences at every leaf.
  • Counting nodes instead of edges, giving an answer one too large on every non-empty path.
  • Comparing the child's value to the root's value rather than to the current node's. That solves the univalued-tree problem instead.
  • Taking max of the two arms for the answer rather than their sum. The sum is the bend, and the bend is often the longest path.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def longestUnivaluePath(self, root):
        self.best = 0
        def dfs(node):
            if not node: return 0
            l = dfs(node.left); r = dfs(node.right)
            lp = l + 1 if node.left and node.left.val == node.val else 0
            rp = r + 1 if node.right and node.right.val == node.val else 0
            self.best = max(self.best, lp + rp)
            return max(lp, rp)
        dfs(root)
        return self.best
Asked at Snowflake Sprinklr
SensAI
Beta
Tap the mic to stop voice mode