My tree type is
type 'a tree = Tree of 'a * 'a tree list;;
How can I get the mirror image of a tree like this? For me is confusing having a list of children, because I do not know how to get individually to each child and do the recursion whitout losing the parent's track, any idea?
EDITED: I have kept trying and I think I got the solution:
let spec arbol =
match arbol with
Tree(a,[])-> Tree(a,[])
| Tree(a,l)-> Tree(a, List.rev (
let rec aux = function
Tree(a,[])::[]->Tree(a,[])::[]
| Tree(a,[])::l-> [Tree(a,[])]@(aux l)
| Tree(a,t)::[]-> [Tree(a, (List.rev (aux t)))]
| Tree(a,t)::l-> [Tree(a, (List.rev (aux t)))]@(aux l)
in aux l));;
I have tried it with this tree:
let p = Tree(1, [
Tree(2,[]);
Tree(3, [
Tree(6,[]);
Tree(7,[])
]);
Tree(4,[]);
Tree(5,[])
]);;
And I got as result of # spec p;;
-: int tree = Tree (1, [
Tree (5,[]);
Tree (4,[]);
Tree (3,[
Tree(7,[]);
Tree(6,[])]);
Tree (2,[])
])
So I guess my function works as expected. Let me know if it is not correct
If I understand the function you're trying to compute, there is a very simple answer that takes one line of code.
Unfortunately your code introduces so many cases that it's hard to check by eye.
It looks to me like your aux
function is intended to calculate the mirror image of a list of trees. However, it doesn't work on an empty list. If you rewrite aux
to work on an empty list, you might find that you won't require so many different cases. In particular, you could remove your outermost match and half the cases in your inner match.
In fact, your aux
function (if correct) does all the work. If you look at it properly, you could just use aux
for everything.
Since you're using List.rev
, I assume you could also use List.map
. That would be something to look at also.
Update
Trees are inherently recursive structures, so when looking for a tree algorithm, it often helps to imagine how you would use your algorithm recursively. In this case, you could ask yourself how you would put together mirror images of all the subtrees of a tree to make a mirror image of the whole tree.
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.