const remove = (root, data) => {
  const removeNode = function (node, data) {
    if (node == null) {
      return null
    }

    if (data === node.val) {
      // node has no children
      if (node.left == null && node.right == null) {
        return null
      }
      // node has no left child
      if (node.left == null) {
        return node.right
      }
      // node has no right child
      if (node.right == null) {
        return node.left
      }
      // node has two children
      var tempNode = node.right
      while (tempNode.left !== null) {
        tempNode = tempNode.left
      }
      node.val = tempNode.val
      node.right = removeNode(node.right, tempNode.val)
      return node
    } else if (data < node.val) {
      node.left = removeNode(node.left, data)
      return node
    } else {
      node.right = removeNode(node.right, data)
      return node
    }
  }

  removeNode(root, data)
}

module.exports = remove
