【发布时间】:2019-04-16 19:40:54
【问题描述】:
我想在 OCaml 中使用队列在二叉树上创建广度优先搜索,但我无法让它工作。
当节点没有任何“邻居”时,函数似乎卡住了。
let rec enque v l =
match l with
[] -> [v]
| h::t -> h::(enque v t)
let rec qhd l =
match l with
h::[] -> h
| h::t -> qhd t
let deque l =
match l with
[] -> []
| h::t -> t
let notempty l = (l != [])
let rec breadthFirstHelp l =
if notempty l
then
let cur = qhd l in
match cur with
Empty -> []
| (Node(Empty, node, Empty)) -> node::(breadthFirstHelp (deque l))
| (Node(left, node, right)) ->
let l = enque right l in
let l = enque left l in
node::(breadthFirstHelp (deque l))
else []
这是我正在测试的一棵树。
[tree =
Node
(Node
(Node (Empty, "A", Empty), "B",
Node (Node (Empty, "C", Empty), "D", Empty)),
"E", Node (Empty, "F", Node (Empty, "G", Node (Empty, "O", Empty))))]
使用我的代码:["E"; “乙”; “一个”; “一个”; "A"]
预期结果:["E"; “乙”; “F”; “一个”; “D”; “G”; “C”; "O"]
【问题讨论】:
标签: tree ocaml binary-tree binary-search-tree breadth-first-search