recursion - F# 如何展平二叉搜索树

标签 recursion functional-programming f# tail-recursion continuation-passing

我有一棵树,结构如下:

type 'a Tree =| Leaf of 'a| Branch of 'a Tree * 'a Tree

我正在我的树上使用连续传递风格的尾递归并尝试将其展平。

let rec loop tree k acc = 
  match tree with
  | Leaf v -> v :: acc
  | Branch (tl,tr) -> loop tl (loop tr k) acc
loop xs id []


(Branch (Branch (Leaf 1.0,Leaf 2.0),Branch (Leaf 3.0,Leaf 4.0)))

这仅返回[1.0]

但是我只得到树中的第一片叶子,我的函数不适用于整个树。我怎样才能实现这一目标?

最佳答案

您正在传递一个延续,但您没有在任何地方调用它。试试这个:

let rec loop tree k acc = 
  match tree with
  | Leaf v -> k (v :: acc)
  | Branch (tl,tr) -> loop tl (loop tr k) acc

然后loop xs id []产生[4.0; 3.0; 2.0; 1.0]

关于recursion - F# 如何展平二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53210613/

相关文章:

javascript - 递归函数错误在第二次运行时跳过数组中的第一个元素

haskell - 为什么应该在函数式编程中使用应用仿函数?

haskell - (=<<) 组合子的鸟名?

f# - 如何隐藏 F# Program.fs 中的记录?

C 将字符串构建为递归遍历二叉树

javascript - 在 javascript 中编写向嵌套数组的每个对象添加属性的算法有哪些方法?

递归中的 Java decToHex - 错误的输出顺序

math - 自由定理和参数化

haskell - Haskell 模式匹配的 F# 版本

.net - F# 和自动向上转换 : sometimes it does, 有时不会,这背后的基本原理是什么?