【问题标题】:OCaml Binary Tree Mirror ImageOCaml 二叉树镜像
【发布时间】:2017-10-31 03:18:38
【问题描述】:

我正在为一门课学习 OCaml,并被分配计算二叉树的镜像。我很困惑,甚至不知道如何开始......

type btree = Empty | Node of int * btree * btree
;;

let mirror : btree -> btree
  = fun t -> (* Code *)

示例输入:

let tree1 = Node(1, Node(2, Node(3, Empty, Empty), Empty), Node(4, Empty, Empty))
;;

样本输出:

mirror tree1 = Node(1, Node(4, Empty, Empty), Node(2, Empty, Node(3, Empty, Empty)))
;;

【问题讨论】:

  • 从简单的开始:镜像 Node(1,Empty, Empty) 的代码可能是什么?节点(1,节点(2,空,空),空)?然后概括(见下面Jin的答案)。发布您的试验 - 然后您将有更多机会获得帮助。
  • 通常在 ML 中你会使用模式匹配,但有趣的是你(或你的导师)给出的样本类似于 s-expressions

标签: ocaml binary-tree mirror


【解决方案1】:

使用match 功能。

您可以match 按其类型定义的值的结构。在您的示例中,btree 类型的值是使用 Empty 构造函数或 Node of int * btree * btree 的元组构造函数创建的。你应该得到这样的结果:

...
match t with
| Node (num, lt, rt) -> (* do something to switch the subtrees, and mirror the subtrees themselves *)
| Empty -> (* do nothing *)
...

由于mirror 函数的类型为btree -> btree,因此您的每个匹配案例都必须返回btree 类型的有效值。

见:http://ocaml.org/learn/tutorials/data_types_and_matching.html#Pattern-matching-on-datatypes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    相关资源
    最近更新 更多