/*
"Height" in a tree represents:
the distance from the root node to any given leaf node.
*/

/**
 * A tree is "balanced" if:
 * the difference between the `min height` and the `max height` will be different at most 1
 */
const isBalanced = () => {
  return this.findMinHeight() >= this.findMaxHeight() - 1
}

/**
 * The max height isthe distance from the root node to
 * whatever the the most bottom node is.
 *
 */
const findMaxHeight = (node) => {
  if (node == null) {
    return -1
  }

  let left = findMaxHeight(node.left)
  let right = findMaxHeight(node.right)

  if (left > right) {
    return left + 1
  } else {
    return right + 1
  }
}

/**
 * The min height is the distance from the root node
 * to the first leaf node without two children
 *
 */
const findMinHeight = (node) => {
  if (node == null) {
    return -1
  }

  let left = findMinHeight(node.left)
  let right = findMinHeight(node.right)

  if (left < right) {
    return left + 1
  } else {
    return right + 1
  }
}

module.exports = {
  isBalanced,
  findMaxHeight,
  findMinHeight
}
