Skip to content

Instantly share code, notes, and snippets.

@natsukium
Created July 20, 2021 12:23
Show Gist options
  • Save natsukium/8ccad1afb3ed8c31aa6d8cefe8e7382b to your computer and use it in GitHub Desktop.
Save natsukium/8ccad1afb3ed8c31aa6d8cefe8e7382b to your computer and use it in GitHub Desktop.
BFS without queue
type 'a Tree =
| Leaf
| Node of 'a * 'a Tree * 'a Tree
let bfs (tree: 'a Tree) =
[ tree ]
|> Seq.unfold
(function
| [] -> None
| h :: t ->
match h with
| Leaf -> Some(None, t)
| Node (x, l, r) -> Some(Some(x), t @ [ l; r ]))
|> Seq.filter Option.isSome
|> Seq.map Option.get
let t =
Node(0, Node(1, Node(3, Leaf, Leaf), Leaf), Node(2, Leaf, Node(4, Leaf, Leaf)))
bfs t |> printfn "%A"
//seq [0; 1; 2; 3; 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment