我的树定义如下:(只是为了更好地理解,我的数据类型要复杂得多。)
type tree = {
mutable value : int;
mutable nodes : tree list
}
我需要找到一个0和1的序列,如下图:
1
|
0 0
\ /
1
|
1
输出将是根和 0 和 1 的序列。这是我的代码:(我假设该序列仅在树的值为 0 的节点(树列表)只有一个元素时才会出现,但我需要改变它,因为它没有必要。)
let rec getSequence tree =
match tree.value with
| 0 ->
if (List.length tree.nodes) = 1 then
let nextTree = List.hd tree.nodes in
match nextTree.value with
| 1 ->
nextTree.nodes <- [];
tree.nodes <- [nextTree];
[tree]
| 0 -> List.concat (List.map (fun t -> getSequence t) nextTree.nodes)
else List.concat (List.map (fun t -> getSequence t) tree.nodes)
| 1 -> List.concat (List.map (fun t -> getSequence t) tree.nodes)
由于某种原因,当我执行代码时,会引发异常 Stack_overflow。任何人都可以帮助我吗?