Skip to content
TheChatArchiveThe Chat Archive
DeepSeekdeepseek-v3-0324· DeepSeekHugging Face LMArena Human Preference 140K

Write a function in Elixir that calculates the depth of a tree.

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-sonnet-20241022’s answer.
  1. User

    Write a function in Elixir that calculates the depth of a tree.

  2. DeepSeek Assistant

    Elixir Function to Calculate Tree Depth

    Here's a function in Elixir that calculates the depth of a tree. I'll assume the tree is represented as a tuple where each node is either:

    • nil for an empty tree
    • {value, left_child, right_child} for a node with children
    defmodule TreeDepth do
      @doc """
      Calculates the maximum depth of a binary tree.
    
      ## Examples
    
          iex> TreeDepth.depth(nil)
          0
    
          iex> TreeDepth.depth({1, nil, nil})
          1
    
          iex> TreeDepth.depth({1, {2, nil, nil}, {3, {4, nil, nil}, nil}})
          3
      """
      def depth(nil), do: 0
      
      def depth({_value, left, right}) do
        1 + max(depth(left), depth(right))
      end
    end
    

    Explanation:

    1. The base case is when the tree is nil (empty), which has depth 0.
    2. For a non-empty node, we calculate the depth as:
      • 1 (for the current node)
      • Plus the maximum of the depths of the left and right subtrees
    3. The function uses recursion to traverse both subtrees.

    Alternative Representation:

    If your tree uses a different structure (like a struct), here's how you might adapt it:

    defmodule Node do
      defstruct value: nil, left: nil, right: nil
    end
    
    defmodule TreeDepth do
      def depth(nil), do: 0
      def depth(%Node{left: left, right: right}) do
        1 + max(depth(left), depth(right))
      end
    end
    

    Usage Example:

    tree = {1, 
            {2, nil, nil}, 
            {3, 
             {4, nil, nil}, 
             nil}}
    
    TreeDepth.depth(tree)  # Returns 3
    

    This implementation follows the standard depth calculation for binary trees with O(n) time complexity where n is the number of nodes.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.