LeetCode-in-All

102. Binary Tree Level Order Traversal

Medium

Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).

Example 1:

Input: root = [3,9,20,null,null,15,7]

Output: [[3],[9,20],[15,7]]

Example 2:

Input: root = [1]

Output: [[1]]

Example 3:

Input: root = []

Output: []

Constraints:

Solution

# Definition for a binary tree node.
#
# defmodule TreeNode do
#   @type t :: %__MODULE__{
#           val: integer,
#           left: TreeNode.t() | nil,
#           right: TreeNode.t() | nil
#         }
#   defstruct val: 0, left: nil, right: nil
# end

defmodule Solution do
  @spec level_order(root :: TreeNode.t | nil) :: [[integer]]
  def level_order(root) do
    solve(compact([root]), [])
  end
    
  defp solve([], acc), do: Enum.reverse(acc)

  defp solve(layer, acc) do
    values = Enum.map(layer, & &1.val)
    next_layer = layer |> Enum.flat_map(&[&1.left, &1.right]) |> compact()
    solve(next_layer, [values | acc])
  end
    
  defp compact(list) do
    Enum.reject(list, &is_nil/1)  
  end
end