Longest Univalue Path (LeetCode 687): Solution and Explanation
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
- Keep a global
best = 0. arm(node)returns 0 for null. Otherwise it first computesarm(left)andarm(right).- If the left child exists and has the same value,
left = arm(left) + 1, elseleft = 0. Same for the right side. - Update
best = max(best, left + right): that is the path bending at this node. - Return
max(left, right)to the parent and finally returnbest.
Step-by-step example
root = [5,4,5,1,1,null,5]
- The leaves 1, 1 and the lower 5 return 0.
- Node 4: both children are 1, which differ, so both arms are 0. best stays 0.
- Right node 5: its right child 5 matches, so right arm = 0 + 1 = 1. best = 1. It returns 1.
- Root 5: left child 4 differs (arm 0), right child 5 matches (arm 1 + 1 = 2). best = 0 + 2 = 2.
- 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.best1class Solution {
2 private int best;
3 public int longestUnivaluePath(TreeNode root) {
4 best = 0;
5 arm(root);
6 return best;
7 }
8 private int arm(TreeNode node) {
9 if (node == null) return 0;
10 int left = arm(node.left);
11 int right = arm(node.right);
12 left = (node.left != null && node.left.val == node.val) ? left + 1 : 0;
13 right = (node.right != null && node.right.val == node.val) ? right + 1 : 0;
14 best = Math.max(best, left + right);
15 return Math.max(left, right);
16 }
17}1class Solution {
2public:
3 int longestUnivaluePath(TreeNode* root) {
4 best = 0;
5 arm(root);
6 return best;
7 }
8private:
9 int best = 0;
10 int arm(TreeNode* node) {
11 if (!node) return 0;
12 int left = arm(node->left);
13 int right = arm(node->right);
14 left = (node->left && node->left->val == node->val) ? left + 1 : 0;
15 right = (node->right && node->right->val == node->val) ? right + 1 : 0;
16 best = max(best, left + right);
17 return max(left, right);
18 }
19};Time and space complexity
O(n)
Every node is visited once and does constant work.
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.