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
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:
nilfor 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 endExplanation:
- The base case is when the tree is
nil(empty), which has depth 0. - 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
- 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 endUsage Example:
tree = {1, {2, nil, nil}, {3, {4, nil, nil}, nil}} TreeDepth.depth(tree) # Returns 3This implementation follows the standard depth calculation for binary trees with O(n) time complexity where n is the number of nodes.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.