Advertisement
joharido

Untitled

Apr 3rd, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.21 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. if (root.value < firstKey)
  17.     rootNode(root.right, firstKey, secondKey);
  18. end IF
  19. else if(root.value > secondKey)
  20.     rootNode(root.left, firstKey, secondKey);
  21. end ELSE IF
  22. else return (left(root, firstKey) + right(root, secondKey) + 1);
  23. END
  24.  
  25. /* this algorithm computes the number of right elements in the range, in the left sub-tree.
  26. pre-condition: a node in the tree and the begining of the given range are passed through.  
  27. post-condition: number of right elements in the range, in the left sub-tree is returned.
  28. Algortihm left(Node node, int firstKey)
  29.     if (node.value > firstKey)
  30.         return (node.right.size + 1 + left(node.left, firstKey));
  31.     end IF
  32.     else if (node.value < firstKey)
  33.         return (left(node.right, firstKey));
  34.     end ELSE IF
  35.     else
  36.         return (node.right.size + 1);
  37.     end ELSE
  38. END
  39.  
  40. /* this algorithm computes the number of right elements in the range, in the right sub-tree.
  41. pre-condition: a node in the tree and the end of the given range are passed through.  
  42. post-condition: number of right elements in the range, in the right sub-tree is returned. */
  43. Algortihm right(Node node, int secondKey)
  44.     if (node.value > secondKey)
  45.         return (right(left.size));
  46.     end IF
  47.     else if (node.value < secondKey)
  48.         return (node.left.size + 1 + right(node.right, secondKey);
  49.     end ELSE IF
  50.     else
  51.         return (node.left.size + 1);
  52.     end ELSE
  53. END
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement