object DiameterOfBinaryTree { case class TreeNode(value: Int, left: Option[TreeNode], right: Option[TreeNode]) def diameterOfBinaryTree(root: Option[TreeNode]): Int = { var diameter = 0 def depth(node: Option[TreeNode]): Int = { node match { case Some(n) => val leftDepth = depth(n.left) val rightDepth = depth(n.right) diameter = math.max(diameter, leftDepth + rightDepth) math.max(leftDepth, rightDepth) + 1 case None => 0 } } depth(root) diameter } def main(args: Array[String]): Unit = { // Example binary tree: // 1 // / \ // 2 3 // / \ // 4 5 val tree = Some(TreeNode(1, Some(TreeNode(2, Some(TreeNode(4, None, None)), Some(TreeNode(5, None, None)))), Some(TreeNode(3, None, None)))) val result = diameterOfBinaryTree(tree) println(s"Diameter of the binary tree: $result") } }