Write a function in Elixir that calculates the depth of a tree.
- User
Write a function in Elixir that calculates the depth of a tree.
Assistant
I'll help you write a function to calculate the depth (or height) of a tree in Elixir. I'll assume we're working with a binary tree structure where each node has a value and left/right children.
defmodule Tree do # Define the tree node structure defstruct value: nil, left: nil, right: nil # Calculate depth of the tree def depth(nil), do: 0 def depth(%Tree{left: left, right: right}) do 1 + max(depth(left), depth(right)) end endThis solution:
- Defines a Tree struct with value, left, and right fields
- Uses pattern matching to handle the base case (nil node returns 0)
- For non-nil nodes, recursively calculates:
- The depth of left subtree
- The depth of right subtree
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.