# Definition for a binary tree node.
# 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: Optional[TreeNode]) -> int:
ans = 0
def dfs(node: Optional[TreeNode]) -> int:
if node is None:
return 0
left = dfs(node.left)
right = dfs(node.right)
left1 = left + 1 if node.left and node.left.val == node.val else 0
right1 = right + 1 if node.right and node.right.val == node.val else 0
nonlocal ans
ans = max(ans, left1 + right1)
return max(left1, right1)
dfs(root)
return ans
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func longestUnivaluePath(root *TreeNode) (ans int) {
var dfs func(*TreeNode) int
dfs = func(node *TreeNode) int {
if node == nil {
return 0
}
left := dfs(node.Left)
right := dfs(node.Right)
left1, right1 := 0, 0
if node.Left != nil && node.Left.Val == node.Val {
left1 = left + 1
}
if node.Right != nil && node.Right.Val == node.Val {
right1 = right + 1
}
ans = max(ans, left1+right1)
return max(left1, right1)
}
dfs(root)
return ans
}
func max(a, b int) int {
if b > a {
return b
}
return a
}