Advertisement
Guest User

Untitled

a guest
Sep 28th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. find is a function that operates on a tree and returns an option (None or SOME(X)).. A tree = EMPTY | Node(L,X,R) where L,R are trees, X is an integer. L is the left subtree, R is the right subtree.
  2.  
  3. The above function finds the ith element of an in-order traversal of tree T, using a helper
  4. function size, which finds the size of any given tree. Assume size(T) has O(n) work where
  5. n is the number of nodes in T\
  6.  
  7.  
  8. type of find : int*tree -> Option(int)
  9.  
  10. (*operating on a case of an empty tree*)
  11. fun find(i, Empty) = NONE
  12.  
  13.  
  14. (*operating on a full tree*)
  15. fun find(i, Node(l, x, r)) =
  16. case find(i, l) of (recursive call to find (i,L) where
  17. SOME(y) => SOME(y)
  18. | NONE => if i = (size l) + 1 then SOME(x)
  19. else find(i - (size l) - 1, r)
  20.  
  21. in java it's
  22.  
  23. #find value at index i in the inorder rep of
  24. int find_at_i(int i, Tree t) {
  25. int j = find_at_i(t.left_tree)
  26. switch(j)
  27. {
  28. case -1 => if(i = t.left_tree.size() + 1)
  29. then return t.val
  30. else return find_at_i(i - t.left_tree.size() - 1, t.right_tree)
  31. default => return j;
  32. }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement