{- |
Description: Collect nodes at a given level
Copyright: Copyright (C) 2021 Yoo Chung
License: GPL-3.0-or-later
Maintainer: dev@chungyc.org

Some solutions to "Problems.P62" of Ninety-Nine Haskell "Problems".
-}
module Solutions.P62 (atLevel) where

import           Problems.BinaryTrees

-- | Collect the nodes at a given level in a list
atLevel :: Tree a -> Int -> [a]
atLevel :: forall a. Tree a -> Int -> [a]
atLevel Tree a
Empty Int
_ = []
atLevel (Branch a
x Tree a
_ Tree a
_) Int
1 = [a
x]
atLevel (Branch a
_ Tree a
l Tree a
r) Int
n
  | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1     = Tree a -> Int -> [a]
forall a. Tree a -> Int -> [a]
atLevel Tree a
l (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1) [a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++ Tree a -> Int -> [a]
forall a. Tree a -> Int -> [a]
atLevel Tree a
r (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
-Int
1)
  | Bool
otherwise = [a]
forall a. HasCallStack => a
undefined