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:
[0, 104].-1000 <= Node.val <= 10001000.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.
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.
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.
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.
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.
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.
Python
Java
C++
Go
TypeScript
Rust
JavaScript
C
| Approach | Complexity |
|---|---|
| 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. |
| 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. |
| DFS | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| DFS with Global Maximum | O(n) | O(h) | Best general solution. Efficient for all binary trees and preferred in coding interviews. |
| BFS Tracking Paths | O(n) | O(n) | Useful if already processing the tree level-by-level or avoiding recursion. |
花花酱 LeetCode 687. Longest Univalue Path - 刷题找工作 EP78 • Hua Hua • 9,023 views views
Watch 9 more video solutions →Practice Longest Univalue Path with our built-in code editor and test cases.
Practice on FleetCode