Advertisement
sweet1cris

Untitled

Sep 25th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.68 KB | None | 0 0
  1. public class ClosestNumberBST {
  2.   public int closest(TreeNode root, int target) {
  3.     // Assumptions: the given binary search tree is not null.
  4.     int result = root.key;
  5.     // The closest number has to be on the path of finding
  6.     // the target value in the binary search tree.
  7.     while (root != null) {
  8.       if (root.key == target) {
  9.         return root.key;
  10.       } else {
  11.         if (Math.abs(root.key - target) < Math.abs(result - target)) {
  12.           result = root.key;
  13.         }
  14.         if (root.key < target) {
  15.           root = root.right;
  16.         } else {
  17.           root = root.left;
  18.         }
  19.       }
  20.     }
  21.     return result;
  22.   }
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement