Untitled

 avatar
ibassi
java
2 years ago
837 B
2
Indexable
import java.util.*;

class Program {
  public static int findClosestValueInBst(BST tree, int target) {
    return findClosestValueInBst(tree, target, tree.value);
  }

  private static int findClosestValueInBst(BST tree, int target, int closest) {
    int diffWithCurr = Math.abs(tree.value - target);
    if (diffWithCurr < Math.abs(closest - target)) {
      closest = tree.value;
    }
    if (tree.value < target && tree.right != null) {
      return findClosestValueInBst(tree.right, target, closest);
    }
    else if (tree.value > target && tree.left != null) {
      return findClosestValueInBst(tree.left, target, closest);
    }
    else {
      return closest;
    }
  }

  static class BST {
    public int value;
    public BST left;
    public BST right;

    public BST(int value) {
      this.value = value;
    }
  }
}
Editor is loading...