user1838768
user1838768

Reputation: 143

Add a whole list of integers to binary tree F#

I have this code

type Tree<'T when 'T: comparison> = 
| Empty 
| Node of 'T * Tree<'T> * Tree<'T>

let rec insert value = function
| Empty -> Node(value, Empty, Empty)
| Node(v, left, right) when value < v -> Node(v, insert value left, right)
| Node(v, left, right) when value > v -> Node(v, left, insert value right)
| Node(_, _, _) as n -> n    

but insteed of adding one integer I want to add a whole list of integers. Example:

let tree = addList [5;2;1;6;7];;

and the list should be added to the tree

Upvotes: 1

Views: 556

Answers (1)

Panos
Panos

Reputation: 627

You can simply do a fold like this

let tree = List.fold (fun tree x -> inser­t x tree)­ Empty­ [5;2;1;6;7];;

At each step you return a new tree, to which you add the next element during the next step. Instead of Empty you can use any existing tree to which you want to add the list of elements.

Upvotes: 5

Related Questions