Skip to main content

Longest Univalue Path - Solution & Explanation

MediumTreeDepth-First SearchBinary Tree27 min readAsked at: Amazon, Meta, Snowflake +4
Practice this problem

Problem Statement

Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.

The length of the path between two nodes is represented by the number of edges between them.

 

Example 1:

Input: root = [5,4,5,1,1,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 5).

Example 2:

Input: root = [1,4,5,4,4,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 4).

 

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -1000 <= Node.val <= 1000
  • The depth of the tree will not exceed 1000.

Approach Overview

Problem Overview: Given a binary tree, find the length of the longest path where every node in the path has the same value. The path can go through any node but must follow parent-child connections. The result is measured in number of edges, not nodes.

Approach 1: Depth First Search (DFS) with Global Maximum (O(n) time, O(h) space)

This approach performs a postorder traversal using Depth-First Search. For each node, recursively compute the longest same-value path extending from its left and right children. If a child has the same value as the current node, extend the path length by 1; otherwise the contribution from that child becomes 0. The key insight is that the longest path passing through a node can combine the left and right extensions, so you update a global maximum with leftPath + rightPath. The DFS function returns the longest single-direction path (either left or right) so the parent can extend it. Since every node is visited exactly once, the algorithm runs in O(n) time with recursion stack space O(h), where h is the tree height.

This method works naturally with tree recursion and is the standard optimal solution used in most editorials. It efficiently captures the idea that the best path through a node may join two matching-value branches.

Approach 2: Breadth First Search for Tracking Paths (O(n) time, O(n) space)

An alternative strategy uses Binary Tree traversal with Breadth-First Search. Traverse the tree level by level and track potential path expansions from each node whose children share the same value. For every node, examine whether the left or right child continues a univalue chain and compute path lengths while keeping a global maximum. BFS requires additional structures (queues or maps) to track intermediate path lengths for nodes, which increases memory usage to O(n).

While BFS can solve the problem, it tends to be less intuitive because the longest path may span across two subtrees and requires combining information from children. DFS naturally handles this bottom-up aggregation.

Recommended for interviews: The DFS with global maximum approach is what interviewers expect. It demonstrates strong understanding of tree recursion and postorder aggregation. Showing how each node contributes a single-direction path upward while updating a global answer proves you understand how to combine subtree results efficiently. BFS works but is rarely the preferred explanation in interviews.

Approach 1: Depth First Search (DFS) with Global Maximum

This approach utilizes a post-order traversal (DFS) to explore all nodes of the binary tree. For each node, we calculate the univalue path length for both the left and right subtrees. We update the global maximum univalue path length during the traversal. The key idea is to compute the longest path length for each node based on whether its children have the same value.

This C solution defines a TreeNode structure and uses a depth-first search to calculate the longest univalue path at each node. We maintain a global variable to store the maximum path length globally.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time complexity: O(n), where n is the number of nodes in the tree, since we visit each node exactly once.
Space complexity: O(h), where h is the height of the tree. This space is used by the recursion stack.

Try this approach in the editor β†’

Approach 2: Breadth First Search for Tracking Paths

This approach uses the Breadth First Search (BFS) method to traverse the tree level by level. As we traverse each level, we compute the longest univalue paths extending from the current node. The maximum path length is globally tracked using a queue to manage the current node and its depth in the tree.

This Java version employs a BFS strategy using a queue, iterating level by level to compute longest univalue paths and updating a maximum counter.

Code

Java

Python

C#

Complexity

Time complexity: O(n^2) in the worst case due to nested calls to traverse each node and its children. However, can perform better on average.
Space complexity: O(n) for managing the queue size in the same level.

Try this approach in the editor β†’

Approach 3: DFS

We design a function dfs(root), which represents the longest univalue path length extending downward with the root node as one endpoint of the path.

In dfs(root), we first recursively call dfs(root.left) and dfs(root.right) to get two return values l and r. These two return values represent the longest univalue path lengths extending downward with the left and right children of the root node as one endpoint of the path, respectively.

If the root has a left child and root.val = root.left.val, then the longest univalue path length extending downward with the left child of the root as one endpoint of the path should be l + 1; otherwise, this length is 0. If the root has a right child and root.val = root.right.val, then the longest univalue path length extending downward with the right child of the root as one endpoint of the path should be r + 1; otherwise, this length is 0.

After recursively calling the left and right children, we update the answer to max(ans, l + r), which is the longest univalue path length passing through the root with the root as one endpoint of the path.

Finally, the dfs(root) function returns the longest univalue path length extending downward with the root as one endpoint of the path, which is max(l, r).

In the main function, we call dfs(root) to get the answer.

The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes in the binary tree.

Code

Python

Java

C++

Go

TypeScript

Rust

JavaScript

C

Try this approach in the editor β†’

Complexity Comparison

ApproachComplexity
Depth First Search (DFS) with Global Maximum

Time complexity: O(n), where n is the number of nodes in the tree, since we visit each node exactly once.
Space complexity: O(h), where h is the height of the tree. This space is used by the recursion stack.

Breadth First Search for Tracking Paths

Time complexity: O(n^2) in the worst case due to nested calls to traverse each node and its children. However, can perform better on average.
Space complexity: O(n) for managing the queue size in the same level.

DFSβ€”

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
DFS with Global MaximumO(n)O(h)Best general solution. Efficient for all binary trees and preferred in coding interviews.
BFS Tracking PathsO(n)O(n)Useful if already processing the tree level-by-level or avoiding recursion.

Video Solution

θŠ±θŠ±ι…± LeetCode 687. Longest Univalue Path - εˆ·ι’˜ζ‰Ύε·₯作 EP78 β€’ Hua Hua β€’ 9,027 views views

Watch 9 more video solutions β†’

Frequently Asked Questions

Is Longest Univalue Path easy or hard?
Longest Univalue Path is considered a Medium difficulty problem on LeetCode. The challenge lies in correctly combining left and right subtree paths while ensuring only nodes with equal values extend the path.
Longest Univalue Path Python/Java solution
Python and Java implementations typically use recursive DFS. Each recursive call returns the longest same-value path extending from the current node, while a global variable stores the maximum path found anywhere in the tree.
How to solve Longest Univalue Path in O(n)?
Use a postorder DFS traversal. For each node, compute the longest path from the left and right child that continues the same value. If a child matches the node's value, extend that path by one edge. Update a global maximum with the sum of both sides and return the longer side to the parent.
What is the best approach for Longest Univalue Path?
Depth First Search with a global maximum is the most effective approach. A postorder traversal calculates the longest same-value path from each node's left and right children, then updates a global answer using leftPath + rightPath. This method visits every node once, giving O(n) time complexity.
Is Longest Univalue Path asked at Google/Amazon/Meta?
Tree DFS problems similar to Longest Univalue Path frequently appear in interviews at companies like Amazon, Google, and Meta. Interviewers use variations of tree path problems to test recursion, postorder traversal, and the ability to combine results from subtrees.
What data structure is used in Longest Univalue Path?
The problem uses a binary tree as the primary data structure. The optimal algorithm applies Depth-First Search recursion to traverse the tree and compute path lengths from child nodes back to their parent.
What is the time complexity of Longest Univalue Path?
The optimal solution runs in O(n) time because each node in the binary tree is processed exactly once during DFS traversal. The recursion stack uses O(h) space, where h is the height of the tree. In the worst case of a skewed tree, space can reach O(n).

Ready to solve this problem?

Practice Longest Univalue Path with our built-in code editor and test cases.

Practice on FleetCode