简体   繁体   中英

OCaml Binary Tree Mirror Image

I'm learning OCaml for a class, and was given an assignment of computing the mirror image of a binary tree. I'm quite stuck and am not sure how to even start...

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

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

Sample input:

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

Sample output:

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

Use the match feature.

You can match on the value's structure as defined by its type. In your example, a value of the btree type is created with either the Empty constructor or a tuple constructor of Node of int * btree * btree . You should end up with something like this:

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

and since the mirror function is of type btree -> btree , each of your match cases must return a valid value of type btree .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM