Advertisement
Guest User

Лабораторная работа №3 Представление и обработка деревьев

a guest
May 4th, 2014
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.27 KB | None | 0 0
  1. type 'T tree =
  2.  | Node of 'T * ('T tree list)
  3.  | Leaf of 'T
  4.  
  5. type 'T bintree =
  6.    | BinNode of 'T * 'T bintree * 'T bintree
  7.     | BinLeaf of 'T
  8. // ----- SAMPLES -----
  9.  
  10. let rec printTree(t: 'T tree) =
  11.     match t with
  12.     | Node(v, ls) -> printfn "Node"; ls |> List.iter printTree
  13.     | Leaf(v)     -> printfn "Leaf"
  14. let sampleTree    = Node(3, [Leaf(4); Leaf(6)])
  15. //printTree(sampleTree)
  16.  
  17. //Node
  18. //Leaf
  19. //Leaf
  20.  
  21. let sampleBinTree = BinNode(3, BinLeaf(4), BinLeaf(6))
  22. let rec printBinTree(t: 'T bintree) =
  23.    match t with
  24.    | BinNode(v, l, r) -> printfn "BinNode"; printBinTree l; printBinTree r
  25.    | BinLeaf(v)       -> printfn "BinLeaf"
  26. //printBinTree(sampleBinTree)
  27.  
  28. // BinNode
  29. // BinLeaf
  30. // BinLeaf
  31.  
  32. // ----- SOLUTION(ВАРИАНТ 14) -----
  33.  
  34. let generateBinTree =
  35.    let rnd = System.Random()
  36.    let rec gen n =
  37.        if (rnd.Next(100) <= n) then
  38.            (BinNode(0, gen (n - 20), gen (n - 20)))
  39.            else
  40.            (BinLeaf(0))
  41.    gen 100
  42.  
  43. let rec solution(t: 'T bintree) =
  44.     match t with
  45.     |   BinNode(v, l, r) -> (solution l + solution r)
  46.     |   BinLeaf(v) -> 1
  47.  
  48. let generatedBinTree = generateBinTree
  49. printBinTree(generatedBinTree)
  50. printfn "%d" (solution(generateBinTree))
  51.  
  52. System.Console.ReadLine() |> ignore
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement