Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  1. class Solution {
  2.   /**
  3.    * Given a Binary Search Tree and an Integer, returns the Entry in this tree
  4.    * with the smallest key that is strictly larger than k.
  5.    *
  6.    * @param tree
  7.    *     Binary search tree to search in.
  8.    * @param k
  9.    *     The key of the resulting entry should be strictly larger than this k.
  10.    * @return The entry with smallest key, strictly larger than k.
  11.    */
  12.   static Entry higherEntry(BinarySearchTree tree, int k) {
  13.     if(tree == null){
  14.       return null;
  15.     }
  16.     if(tree.getKey() <= k){
  17.       if(tree.hasRight()){
  18.         return higherEntry(tree.getRight(), k);
  19.       }
  20.       return null;
  21.     }
  22.     if (tree.getKey() > k){
  23.       Entry closest = tree.getEntry();
  24.       if(tree.hasLeft()){
  25.         Entry leftEntry = higherEntry(tree.getLeft(), k);
  26.         if(leftEntry == null){
  27.           return closest;
  28.         } else {
  29.           return leftEntry;
  30.         }
  31.       }
  32.     }
  33.     return tree.getEntry();
  34.   }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement