gpt4 book ai didi

javascript - 在类内部定义的函数上获取引用错误 "ReferenceError: insertLevelOrder is not defined"

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:49:34 26 4
gpt4 key购买 nike

我试图使用 javaScript 实现一个完整的二叉树,但我得到了 ReferenceError 的错误:insertLevelOrder is not defined 这里是我的代码:


// 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);

我在最后添加了一些代码来测试算法我不确定哪里出了问题

最佳答案

在类中你必须使用 thisthis.insertLevelOrder(...

我已经删除了您在代码中的注释,并在您必须添加 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);

关于javascript - 在类内部定义的函数上获取引用错误 "ReferenceError: insertLevelOrder is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57242911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com