Advertisement
VladSmirN

F#

Jun 30th, 2021
2,208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.77 KB | None | 0 0
  1. open System
  2. type 't btree =
  3.    Node of 't * 't btree * 't btree
  4.     | Nil
  5. [<EntryPoint>]
  6. let main argv =
  7.  
  8.  
  9.     let infix root left right = (left(); root(); right())  //порядок обхода
  10.     let iterh trav f t =  //обход: здесь trav - функция порядка обхода
  11.         let rec tr t h =
  12.             match t with
  13.                 Node (x,L,R) -> trav
  14.                                     (fun () -> (f x L R h)) // обход корня
  15.                                     (fun () -> tr L (h+1)) // обход левого поддерев
  16.                                     (fun () -> tr R (h+1)); // обход правого поддерева
  17.  
  18.                | Nil -> ()
  19.         tr t 0
  20.                    
  21.                    
  22.  
  23.  
  24.  
  25.  
  26.     let spaces n = List.fold (fun s _ -> s+" ") "" [0..n]
  27.     let print_tree T = iterh  infix (fun x L R h -> printfn "%s%A" (spaces (h+5))x) T
  28.     let rec insert x t =
  29.         match t with
  30.         Nil -> Node(x,Nil,Nil)
  31.         | Node(z,L,R) -> if x<z then Node(z,insert x L,R)
  32.                          else Node(z,L,insert x R)
  33.     let L =
  34.       [
  35.         let r = new Random()
  36.         printfn "Количество элементов?"
  37.         //let n = Convert.ToInt32(Console.ReadLine())  
  38.         let n = 10
  39.         for i in 1..n do
  40.             yield r.Next(-15, 16)
  41.       ]
  42.     printfn "Исходный список %A" L
  43.     let list_to_tree L = List.fold (fun t x ->  insert x t) Nil L
  44.  
  45.     let BT = list_to_tree L
  46.  
  47.     print_tree BT
  48.    
  49.     let print_ans T = iterh  infix (fun x L R h -> if L<>Nil&&R<>Nil then printfn "%A "  x) T
  50.     printfn "Ответ: "
  51.     print_ans BT
  52.     System.Console.ReadLine() |> ignore
  53.     0
  54.    
  55.     // return an integer exit code
  56.  
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement