Leetcode 687. Longest Univalue Path
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.
class Solution {
private int maxLength = 0;
public int longestUnivaluePath(TreeNode root) {
dfs(root);
return maxLength;
}
private int dfs(TreeNode node) {
if (node == null) {
return 0;
}
int leftLength = dfs(node.left);
int rightLength = dfs(node.right);
int leftPath = 0, rightPath = 0;
// Check if left child exists and has the same value as current node
if (node.left != null && node.left.val == node.val) {
leftPath = leftLength + 1;
}
// Check if right child exists and has the same value as current node
if (node.right != null && node.right.val == node.val) {
rightPath = rightLength + 1;
}
// Update the global maxLength
maxLength = Math.max(maxLength, leftPath + rightPath);
// Return the max length of the path extending from current node to its parent
return Math.max(leftPath, rightPath);
}
}
This code ensures that we find the longest univalue path in the given binary tree efficiently by leveraging the properties of DFS and maintaining a global state to track the longest path length.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?