Longest Univalue Path solution and explanation
9 more videos on this problem
花花酱 LeetCode 687. Longest Univalue Path - 刷题找工作 EP78Hua Hua · 8:42 · 9K views
Longest Univalue Path || LeetcodePepcoding · 18:36 · 7K views
(Remade) Longest Univalue Path | Binary Tree | Leetcode 687Nideesh Terapalli · 6:04 · 6K views
Longest Univalue PathDors Coding School · 14:28 · 5K views
LONGEST UNIVALUE PATH | LEETCODE 687 | PYTHON DFS SOLUTIONCracking FAANG · 14:46 · 2K views
LeetCode 687. Longest Univalue PathHappy Coding · 15:50 · 2K views
(Old) Leetcode 687 - Longest Univalue Path | Binary TreeNideesh Terapalli · 5:42 · 2K views
Leetcode - 687 . Longest Univalue Path | DFSRaman Bhari · 16:08 · 1K views
leetcode 687. Longest Univalue Pathalgorithm everyday · 8:43 · 883 views
【每日一题】LeetCode 687. Longest Univalue PathHuifeng Guan · 13:44 · 539 views
The problem
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.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.maxLength = 0
def dfs(self, node):
if not node:
return 0
leftPath = self.dfs(node.left)
rightPath = self.dfs(node.right)
left = right = 0
if node.left and node.left.val == node.val:
left = leftPath + 1
if node.right and node.right.val == node.val:
right = rightPath + 1
self.maxLength = max(self.maxLength, left + right)
return max(left, right)
def longestUnivaluePath(self, root):
self.maxLength = 0
self.dfs(root)
return self.maxLengthclass TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
private int maxLength = 0;
private int dfs(TreeNode node) {
if (node == null) return 0;
int leftPath = dfs(node.left);
int rightPath = dfs(node.right);
int left = 0, right = 0;
if (node.left != null && node.left.val == node.val) {
left = leftPath + 1;
}
if (node.right != null && node.right.val == node.val) {
right = rightPath + 1;
}
maxLength = Math.max(maxLength, left + right);
return Math.max(left, right);
}
public int longestUnivaluePath(TreeNode root) {
maxLength = 0;
dfs(root);
return maxLength;
}
}#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int maxLength = 0;
int dfs(TreeNode* node) {
if (!node) return 0;
int leftPath = dfs(node->left);
int rightPath = dfs(node->right);
int left = 0, right = 0;
if (node->left && node->left->val == node->val) {
left = leftPath + 1;
}
if (node->right && node->right->val == node->val) {
right = rightPath + 1;
}
maxLength = max(maxLength, left + right);
return max(left, right);
}
int longestUnivaluePath(TreeNode* root) {
maxLength = 0;
dfs(root);
return maxLength;
}
};class TreeNode {
constructor(val) {
this.val = val;
this.left = this.right = null;
}
}
var longestUnivaluePath = function(root) {
let maxLength = 0;
const dfs = (node) => {
if (!node) return 0;
const leftPath = dfs(node.left);
const rightPath = dfs(node.right);
let left = 0, right = 0;
if (node.left && node.left.val === node.val) {
left = leftPath + 1;
}
if (node.right && node.right.val === node.val) {
right = rightPath + 1;
}
maxLength = Math.max(maxLength, left + right);
return Math.max(left, right);
};
dfs(root);
return maxLength;
};#include <stdio.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int maxLength = 0;
int dfs(struct TreeNode* node) {
if (!node) return 0;
int leftPath = dfs(node->left);
int rightPath = dfs(node->right);
int left = 0, right = 0;
if (node->left && node->left->val == node->val) {
left = leftPath + 1;
}
if (node->right && node->right->val == node->val) {
right = rightPath + 1;
}
maxLength = (left + right > maxLength) ? left + right : maxLength;
return (left > right ? left : right);
}
int longestUnivaluePath(struct TreeNode* root) {
maxLength = 0;
dfs(root);
return maxLength;
}public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution {
private int maxLength = 0;
private int Dfs(TreeNode node) {
if (node == null) return 0;
int leftPath = Dfs(node.left);
int rightPath = Dfs(node.right);
int left = 0, right = 0;
if (node.left != null && node.left.val == node.val) {
left = leftPath + 1;
}
if (node.right != null && node.right.val == node.val) {
right = rightPath + 1;
}
maxLength = Math.Max(maxLength, left + right);
return Math.Max(left, right);
}
public int LongestUnivaluePath(TreeNode root) {
maxLength = 0;
Dfs(root);
return maxLength;
}
}The Python solution defines a TreeNode class and a Solution class. It uses a DFS approach to explore each node's left and right path lengths, updating a global maximum length variable.
Time complexity: O(n), where n is the number of nodes.
Space complexity: O(h), where h is the height of the tree.
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.
from collections import deque
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def longestUnivaluePath(self, root):
if not root:
return 0
queue = deque([root])
maxLength = 0
def longestPathFromNode(node):
if not node:
return 0
leftPath = longestPathFromNode(node.left) + 1 if node.left and node.left.val == node.val else 0
rightPath = longestPathFromNode(node.right) + 1 if node.right and node.right.val == node.val else 0
return max(leftPath, rightPath)
while queue:
node = queue.popleft()
leftLength = longestPathFromNode(node.left) if node.left and node.left.val == node.val else 0
rightLength = longestPathFromNode(node.right) if node.right and node.right.val == node.val else 0
maxLength = max(maxLength, leftLength + rightLength)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return maxLengthimport java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public int longestUnivaluePath(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int maxLength = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
int leftLength = node.left != null && node.left.val == node.val ? longestPathFromNode(node.left) + 1 : 0;
int rightLength = node.right != null && node.right.val == node.val ? longestPathFromNode(node.right) + 1 : 0;
maxLength = Math.max(maxLength, leftLength + rightLength);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
return maxLength;
}
private int longestPathFromNode(TreeNode node) {
if (node == null) return 0;
int leftPath = node.left != null && node.left.val == node.val ? longestPathFromNode(node.left) + 1 : 0;
int rightPath = node.right != null && node.right.val == node.val ? longestPathFromNode(node.right) + 1 : 0;
return Math.max(leftPath, rightPath);
}
}using System.Collections.Generic;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution {
public int LongestUnivaluePath(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
int maxLength = 0;
while (queue.Count > 0) {
TreeNode node = queue.Dequeue();
int leftLength = node.left != null && node.left.val == node.val ? LongestPathFromNode(node.left) + 1 : 0;
int rightLength = node.right != null && node.right.val == node.val ? LongestPathFromNode(node.right) + 1 : 0;
maxLength = Math.Max(maxLength, leftLength + rightLength);
if (node.left != null) queue.Enqueue(node.left);
if (node.right != null) queue.Enqueue(node.right);
}
return maxLength;
}
private int LongestPathFromNode(TreeNode node) {
if (node == null) return 0;
int leftPath = node.left != null && node.left.val == node.val ? LongestPathFromNode(node.left) + 1 : 0;
int rightPath = node.right != null && node.right.val == node.val ? LongestPathFromNode(node.right) + 1 : 0;
return Math.Max(leftPath, rightPath);
}
}Using Python and a dequeue implementation, this solution employs BFS for calculating longest univalue paths, maintaining a global maximum.
Time complexity: O(n^2) in the worst case due to repetitive traversal within nested calls. In practice, might run faster.
Space complexity: O(n) for storing nodes in a queue.
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.
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function longestUnivaluePath(root: TreeNode | null): number {
let ans: number = 0;
const dfs = (root: TreeNode | null): number => {
if (!root) {
return 0;
}
let [l, r] = [dfs(root.left), dfs(root.right)];
l = root.left && root.left.val === root.val ? l + 1 : 0;
r = root.right && root.right.val === root.val ? r + 1 : 0;
ans = Math.max(ans, l + r);
return Math.max(l, r);
};
dfs(root);
return ans;
}/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func longestUnivaluePath(root *TreeNode) (ans int) {
var dfs func(*TreeNode) int
dfs = func(root *TreeNode) int {
if root == nil {
return 0
}
l, r := dfs(root.Left), dfs(root.Right)
if root.Left != nil && root.Left.Val == root.Val {
l++
} else {
l = 0
}
if root.Right != nil && root.Right.Val == root.Val {
r++
} else {
r = 0
}
ans = max(ans, l+r)
return max(l, r)
}
dfs(root)
return
}// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
fn dfs(root: &Option<Rc<RefCell<TreeNode>>>, target: i32, ans: &mut i32) -> i32 {
if root.is_none() {
return 0;
}
let root = root.as_ref().unwrap().borrow();
let left = Self::dfs(&root.left, root.val, ans);
let right = Self::dfs(&root.right, root.val, ans);
*ans = (*ans).max(left + right);
if root.val == target {
return left.max(right) + 1;
}
0
}
pub fn longest_univalue_path(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
if root.is_none() {
return 0;
}
let mut ans = 0;
Self::dfs(&root, root.as_ref().unwrap().borrow().val, &mut ans);
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Depth First Search (DFS) with Global Maximum | Time complexity: O(n), where n is the number of nodes. |
| Breadth First Search for Tracking Paths | Time complexity: O(n^2) in the worst case due to repetitive traversal within nested calls. In practice, might run faster. |
| DFS | – |
Complexity analysis
| 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. |
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).
