# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
self.ans = 0
def dfs(node):
if not node:
return 0
left = dfs(node.left)
right = dfs(node.right)
left_path = right_path = 0
if node.left and node.left.val == node.val:
left_path = left + 1
if node.right and node.right.val == node.val:
right_path = right + 1
self.ans = max(self.ans, left_path + right_path)
return max(left_path, right_path)
dfs(root)
return self.ans
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int ans = 0;
int dfs(TreeNode* node) {
if (!node) return 0;
int left = dfs(node->left);
int right = dfs(node->right);
int left_path = 0, right_path = 0;
if (node->left && node->left->val == node->val)
left_path = left + 1;
if (node->right && node->right->val == node->val)
right_path = right + 1;
ans = std::max(ans, left_path + right_path);
return std::max(left_path, right_path);
}
int longestUnivaluePath(TreeNode* root) {
dfs(root);
return ans;
}
};
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
private int ans = 0;
public int longestUnivaluePath(TreeNode root) {
dfs(root);
return ans;
}
private int dfs(TreeNode node) {
if (node == null) return 0;
int left = dfs(node.left);
int right = dfs(node.right);
int leftPath = 0, rightPath = 0;
if (node.left != null && node.left.val == node.val)
leftPath = left + 1;
if (node.right != null && node.right.val == node.val)
rightPath = right + 1;
ans = Math.max(ans, leftPath + rightPath);
return Math.max(leftPath, rightPath);
}
}
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
var longestUnivaluePath = function(root) {
let ans = 0;
function dfs(node) {
if (!node) return 0;
let left = dfs(node.left);
let right = dfs(node.right);
let leftPath = 0, rightPath = 0;
if (node.left && node.left.val === node.val) {
leftPath = left + 1;
}
if (node.right && node.right.val === node.val) {
rightPath = right + 1;
}
ans = Math.max(ans, leftPath + rightPath);
return Math.max(leftPath, rightPath);
}
dfs(root);
return ans;
};
5 / \ 4 5 / \ \ 1 1 5The longest univalue path is the two edges connecting the rightmost 5s. So, the output should be
2
.
ans
) to keep track of the global maximum path length found so far.ans
contains the length of the longest univalue path (measured in edges).5 / \ 4 5 / \ \ 1 1 5