Q:

Getting a reference error "ReferenceError: insertLevelOrder is not defined" on function defined inside a class

I was trying to implements a Full Binary Tree usiing javaScript and I got the error of ReferenceError: insertLevelOrder is not defined here is my code:

// given array in level order fashion 
class Node {
    constructor(data, left = null, right = null) {
        this.data = data;
        this.left = left;
        this.right = right;
    }
};

class Tree {
    constructor() {
        this.root = null;
    }

    // Function to insert nodes in level order 
    insertLevelOrder(arr, root, i) 
    { 
        // Base case for recursion 
        if (i < arr.length) { 
            var temp = new Node(arr[i]); 
            root = temp; 

            // insert left child 
            root.left = insertLevelOrder(arr, root.left, 2 * i + 1); 

            // insert right child 
            root.right = insertLevelOrder(arr, root.right, 2 * i + 2); 
        } 
        return root; 
    } 

    // Function to print tree nodes in InOrder fashion 
    inOrder(root) 
    { 
        if (root != null) { 
            inOrder(root.left); 
            console.log(root.data + " "); 
            inOrder(root.right); 
        } 
    } 

} 

var tree = new Tree();
var arr = new Array(1, 2, 3, 4, 5, 6, 6, 6, 6 );
tree.root = tree.insertLevelOrder(arr, tree.root, 0); 

I have added some code at the end to test the algo I'm  not sure whats wrong 

A:

inside the class you have to use this like this.insertLevelOrder(...
I have removed your comments in the code and added comments where you have to add this.

class Node {
    constructor(data, left = null, right = null) {
        this.data = data;
        this.left = left;
        this.right = right;
    }
};

class Tree {
    constructor() {
        this.root = null;
    }

    insertLevelOrder(arr, root, i) 
    { 
        if (i < arr.length) { 
            var temp = new Node(arr[i]); 
            root = temp; 

            // you need to add this.
            root.left = this.insertLevelOrder(arr, root.left, 2 * i + 1); 

            // you need to add this.
            root.right = this.insertLevelOrder(arr, root.right, 2 * i + 2); 
        } 
        return root; 
    } 

    inOrder(root) 
    { 
        if (root != null) { 
            this.inOrder(root.left); // you need to add this.
            console.log(root.data + " "); 
            this.inOrder(root.right); // you need to add this.
        } 
    } 

} 

var tree = new Tree();
var arr = new Array(1, 2, 3, 4, 5, 6, 6, 6, 6 );
tree.root = tree.insertLevelOrder(arr, tree.root, 0); 

