Longest Univalue Path
Medium
Topics
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
null marks a missing child.Input: root = [5,4,5,1,1,null,5] Output: 2
Example 2
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
- Post-order DFS returning the longest matching arm downward.
leftArm = left + 1if the left child exists and matches, else 0; likewise right.- Fold
leftArm + rightArminto the running best. - 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
maxof 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.bestimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int longestUnivaluePath(TreeNode root) {
best = 0;
dfs(root);
return best;
}
int best;
private int dfs(TreeNode node) {
if (node == null) return 0;
int l = dfs(node.left), r = dfs(node.right);
int lp = (node.left != null && node.left.val == node.val) ? l + 1 : 0;
int rp = (node.right != null && node.right.val == node.val) ? r + 1 : 0;
best = Math.max(best, lp + rp);
return Math.max(lp, rp);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int longestUnivaluePath(TreeNode* root) {
int best = 0;
function<int(TreeNode*)> dfs = [&](TreeNode* node) -> int {
if (!node) return 0;
int l = dfs(node->left), r = dfs(node->right);
int lp = (node->left && node->left->val == node->val) ? l + 1 : 0;
int rp = (node->right && node->right->val == node->val) ? r + 1 : 0;
best = max(best, lp + rp);
return max(lp, rp);
};
dfs(root);
return best;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var longestUnivaluePath = function(root) {
let best = 0;
const dfs = (node) => {
if (!node) return 0;
const l = dfs(node.left), r = dfs(node.right);
const lp = (node.left && node.left.val === node.val) ? l + 1 : 0;
const rp = (node.right && node.right.val === node.val) ? r + 1 : 0;
best = Math.max(best, lp + rp);
return Math.max(lp, rp);
};
dfs(root);
return best;
};