Add depth function
This commit is contained in:
parent
3dc6171f8d
commit
a2f059e194
1 changed files with 24 additions and 0 deletions
|
@ -97,4 +97,28 @@ defmodule MbBinaryTree do
|
|||
[12, nil, [4, nil, nil]]
|
||||
"""
|
||||
def update_right([node, left, _right], new_right), do: [node, left, new_right]
|
||||
|
||||
@doc """
|
||||
Calculate the depth of a binary tree.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> MbBinaryTree.depth(nil)
|
||||
0
|
||||
iex> MbBinaryTree.depth([1, nil, nil])
|
||||
1
|
||||
iex> MbBinaryTree.depth([1, [2, nil, nil], [3, nil, nil]])
|
||||
2
|
||||
iex> MbBinaryTree.depth([1, [2, nil, nil], [3, [4, nil, nil], [5, nil, nil]]])
|
||||
3
|
||||
iex> MbBinaryTree.depth([12, [4, MbBinaryTree.new(2), MbBinaryTree.new(5)], [26, MbBinaryTree.new(14), [28, MbBinaryTree.new(27), MbBinaryTree.new(30)]]])
|
||||
4
|
||||
"""
|
||||
def depth(tree) do
|
||||
case tree do
|
||||
nil -> 0
|
||||
[_, nil, nil] -> 1
|
||||
[_, left, right] -> 1 + max(depth(left), depth(right))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Reference in a new issue