Advertisement
joharido

Untitled

Apr 3rd, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.23 KB | None | 0 0
  1. /* this algorithm looks for the common elements in both the given BST and the specified range.
  2. pre-condition: the begining and the end elements of the range.  
  3. post-condition: returns the number of common elements. */
  4. Algortihm countRange(int firstKey, int secondKey)
  5.     return rootNode(tree.root, firstKey, secondKey);
  6. END
  7.  
  8. /*this algorithm keeps checking the root node to make sure it is within the specified given range and if not it keeps going down level by level till it
  9. gets to a node that is within the given range
  10. pre-condition: the given binarysearchtree has nodes with integer values.
  11. The firstKey is the begining of the given range and the second key is the end of the given range
  12. post-condition: the cardinality of the intersection of the range and the binary tree is returned. */
  13. Algortihm countRangeHelper(Node root, int firstKey, int secondKey)
  14. if (root = null)
  15.     return null;
  16. end IF
  17. if (root.value < firstKey)
  18.     rootNode(root.right, firstKey, secondKey);
  19. end IF
  20. else if(root.value > secondKey)
  21.     rootNode(root.left, firstKey, secondKey);
  22. end ELSE IF
  23. else return (left(root, firstKey) + right(root, secondKey) + 1);
  24. END
  25.  
  26. /* this algorithm computes the number of right elements in the range, in the left sub-tree.
  27. pre-condition: a node in the tree and the begining of the given range are passed through.  
  28. post-condition: number of right elements in the range, in the left sub-tree is returned. */
  29. Algortihm left(Node node, int firstKey)
  30.     if (node.value > firstKey)
  31.         return (node.right.size + 1 + left(node.left, firstKey));
  32.     end IF
  33.     else if (node.value < firstKey)
  34.         return (left(node.right, firstKey));
  35.     end ELSE IF
  36.     else
  37.         return (node.right.size + 1);
  38.     end ELSE
  39. END
  40.  
  41. /* this algorithm computes the number of right elements in the range, in the right sub-tree.
  42. pre-condition: a node in the tree and the end of the given range are passed through.  
  43. post-condition: number of right elements in the range, in the right sub-tree is returned. */
  44. Algortihm right(Node node, int secondKey)
  45.     if (node.value > secondKey)
  46.         return (right(left.size));
  47.     end IF
  48.     else if (node.value < secondKey)
  49.         return (node.left.size + 1 + right(node.right, secondKey);
  50.     end ELSE IF
  51.     else
  52.         return (node.left.size + 1);
  53.     end ELSE
  54. END
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement