singularity

Find Closest Value In BST

Understanding the problem

Given a Binary Search Tree and a target integer, we are asked to write a function that is going to return the value in the BST that is closest to the target. We can assume there is only one closest value.

For example,

      10
    /    \
   4      20
 /   \
1     6

target = 5

The closest value to the target is 4.

Iterative Approach

We are going to use a variable to keep track of the current node and initialize it to the root node of the BST. In addition, we also need a variable to keep track of the closest value in the BST so far; initialize it to the value of the root node.

While current node is not null,

Implementation

JavaScript:

function findClosestValueInBst(tree, target) {
  let currNode = tree;
  let currClosestValue = tree.value;

  while (currNode !== null) {
    if (
      Math.abs(currNode.value - target) < Math.abs(currClosestValue - target)
    ) {
      currClosestValue = currNode.value;
    }

    if (target < currNode.value) {
      currNode = currNode.left;
    } else if (target > currNode.value) {
      currNode = currNode.right;
    } else {
      break;
    }
  }

  return currClosestValue;
}

// This is the class of the input tree. Do not edit.
class BST {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

Complexity Analysis

Average Case: O(log(N)), where N is the number of nodes in the Binary Search Tree.

Worst Case: O(N), when the Binary Search Tree has only one branch.

Recursive Approach

The iterative solution above can be rewritten in the recursion form.

Implementation

JavaScript:

function findClosestValueInBst(tree, target) {
  return findClosestValueInBstImpl(tree, target, tree.value);
}

function findClosestValueInBstImpl(tree, target, closestValue) {
  if (Math.abs(tree.value - target) < Math.abs(closestValue - target)) {
    closestValue = tree.value;
  }

  if (target < tree.value && tree.left !== null) {
    return findClosestValueInBstImpl(tree.left, target, closestValue);
  }

  if (target > tree.value && tree.right !== null) {
    return findClosestValueInBstImpl(tree.right, target, closestValue);
  }

  return closestValue;
}

// This is the class of the input tree. Do not edit.
class BST {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

Complexity Analysis

Average Case: O(log(N)), where N is the number of nodes in the Binary Search Tree.

Worst Case: O(N), when the Binary Search Tree has only one branch.