Advertisement
Guest User

Untitled

a guest
Apr 20th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. {-
  2. 5. (BONUS, 1.5p) Arbori binari de căutare
  3. Definiți funcția nodesDistance, care returnează distanța
  4. între două noduri (numărul minim de arce ce trebuie parcurse
  5. pentru a ajunge dintr-un nod în celălalt).
  6. Vom lucra doar pe arbori ce nu conțin valori duplicate!
  7. -}
  8. test5 :: TestPP ()
  9. test5 = tests 5 1.5
  10. [ testVal (nodesDistance t 1 5) (Just 4) "nodesDistance 1, 5" 0.5
  11. , testVal (nodesDistance t 4 5) (Just 2) "nodesDistance 4, 5" 0.5
  12. , testVal (nodesDistance t 2 7) Nothing "nodesDistance 2, 7" 0.5
  13. ]
  14. where
  15. t = makeBST [1, 2, 3, 4, 5, 6]
  16.  
  17. nodesDistance :: (Ord a, Eq a) => BST a -> a -> a-> Maybe Int
  18. nodesDistance t n1 n2
  19. | lowestCommonAncestor t n1 n2 /= Nothing = Just $ (findDistance n1 (retTree (lowestCommonAncestor t n1 n2) t)) + (findDistance n2 (retTree (lowestCommonAncestor t n1 n2) t))
  20. | otherwise = Nothing
  21.  
  22. retTree :: (Ord a, Eq a) => a -> BST a -> BST a
  23. retTree y (BSTNod x s d)
  24. | x == y = (BSTNod x s d)
  25. | x < y = retTree y s
  26. | otherwise = retTree y d
  27.  
  28. findDistance :: (Ord a, Eq a) => a -> BST a -> Int
  29. findDistance y (BSTNod x s d)
  30. | x == y = 0
  31. | x < y = 1 + findDistance y s
  32. | otherwise = 1 + findDistance y d
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement