Advertisement
VladSmirN

F# tree task2

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