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.
The length of the path between two nodes is represented by the number of edges between them.
#include <iostream>
#include <algorithm>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
maxPathLength = 0; // Initialize the maximum path length
dfs(root);
return maxPathLength;
}
private:
int maxPathLength;
int dfs(TreeNode* node) {
if (node == nullptr) return 0;
// Recursively get the longest univalue path in the left and right subtrees
int leftPath = dfs(node->left);
int rightPath = dfs(node->right);
int left = 0, right = 0;
// If left child exists and has the same value, include it in the path
if (node->left && node->left->val == node->val) {
left = leftPath + 1;
}
// If right child exists and has the same value, include it in the path
if (node->right && node->right->val == node->val) {
right = rightPath + 1;
}
// The longest path through the current node is the sum of left and right paths
maxPathLength = std::max(maxPathLength, left + right);
// Return the longest one-side path
return std::max(left, right);
}
};
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?