user1993381
user1993381

Reputation: 179

Adjoining binary trees

I am writing a function that takes 2 binary trees (t1 and t2) and generates a new tree that places t2 at the bottom right of t1. t2 is attached to the first node whose right child is empty, even if the node is not a leaf.

let rec adjoin_right (t1: 'a tree) (t2: 'a tree) : 'a tree

test case:

let test () : bool =
adjoin_right (Node (Empty, 1, Empty)) (Node (Empty, 2, Empty)) = 
Node(Empty, 1, Node (Empty, 2, Empty))
;; run_test "adjoin_right leaf" test

Can somebody steer me in the right direction for this problem? I know that I'll probably have to write a helper function.

Upvotes: 1

Views: 105

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

To make recursion work you just have to think about two questions:

  • What's the result supposed to be if t1 is Empty?

  • If t1 isn't empty, but you had a function that worked properly when applied to the subtrees of t1, how would you use this function to get the result?

If you can figure these out, then you do have a function that works properly for subtrees.

Edit

Consider the recursive case. You have l (your left subtree), r (your right subtree), and v (the value in the node). In FP you're not going to change any of these values. What you want to do is to construct a new tree with the correct contents. So, how would you use your function recursively to make the new tree from these three ingredients? It's not hard--really just one line of code.

Upvotes: 2

Related Questions