Answer for find min/max height of BST incorrect?

https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-find-the-minimum-and-maximum-height-of-a-binary-search-tree/301641

If I create a tree with min height of 2, the solution (plus an add method) returns a min height of 1. Im using the displayTree function provided in the code, where you can see the tree in the console. Maybe Im missing something here but I believe the tree is correctly displayed, I just think the min height function in incorrect.

Solution code + add function as well as tree construction and display

var displayTree = tree => console.log(JSON.stringify(tree, null, 2));

function Node(value) {
  this.value = value;
  this.left  = null;
  this.right = null;
}

function BinarySearchTree() {
  this.root = null;
  // Only change code below this line
      this.add = function(value) {
    const newNode = new Node(value);
    if (!this.root) {
      this.root = newNode;
      return undefined;
    }
    let currentNode = this.root;
    while (currentNode) {
      if (currentNode.value === newNode.value) {
        return null;
      }
      const direction = currentNode.value > newNode.value ? "left" : "right";
      if (!currentNode[direction]) {
        currentNode[direction] = newNode;
        return undefined;
      }
      currentNode = currentNode[direction];
    }
  }
  this.findMinHeight = function() {
    if (!this.root) return -1;

    function findNodeMinHeight(node) {
      if (!node) return 0;
      return 1 + Math.min(
          findNodeMinHeight(node.left),
          findNodeMinHeight(node.right)
        );
    }

    return findNodeMinHeight(this.root) - 1;
  }

  this.findMaxHeight = function() {
    if (!this.root) return -1;

    function findNodeMaxHeight(node) {
      if (!node) return 0;
      return 1 + Math.max(
          findNodeMaxHeight(node.left),
          findNodeMaxHeight(node.right)
        );
    }

    return findNodeMaxHeight(this.root) - 1;
  }

  this.isBalanced = function() {
    return this.findMinHeight() == this.findMaxHeight();
  }
  // Only change code above this line
}
const p = new BinarySearchTree()
p.add(17)
p.add(4)
p.add(1)
p.add(19)
p.add(33)
p.add(34)
console.log(displayTree(p))
console.log(p.findMinHeight(), "min")

console output:

{
  "root": {
    "value": 17,
    "left": {
      "value": 4,
      "left": {
        "value": 1,
        "left": null,
        "right": null
      },
      "right": null
    },
    "right": {
      "value": 19,
      "left": null,
      "right": {
        "value": 33,
        "left": null,
        "right": {
          "value": 34,
          "left": null,
          "right": null
        }
      }
    }
  }
}
undefined
1 min

Answer not incorrect! The definition of min height is distance from the root node to the first leaf node that does not contain two children!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.