Ich habe den folgenden Code, der eine BST-Struktur in JavaScript implementiert.Breite erste Suche binäre Suche Baum Javascript-Implementierung
function Node(value) {
this.left = null;
this.right = null;
this.value = value;
}
function BinarySearchTree() {
this.root = null;
return;
}
BinarySearchTree.prototype.push = function(value) {
if (!this.root) {
this.root = new Node(value);
return;
}
var currentRoot = this.root;
var newNode = new Node(value);
while (currentRoot) {
if (value < currentRoot.value) {
if (!currentRoot.left) {
currentRoot.left = newNode;
break;
} else {
currentRoot = currentRoot.left;
}
} else {
if (!currentRoot.right) {
currentRoot.right = newNode;
break;
} else {
currentRoot = currentRoot.right;
}
}
}
}
var a = new BinarySearchTree();
a.push(27);
a.push(14);
a.push(35);
a.push(10);
a.push(19);
a.push(31);
a.push(42);
Ich versuche, eine Funktion zu implementieren, die eine Breite ersten Traversal des Baumes tun. Das habe ich bisher versucht.
console.log(a.root.value);
traverse(a.root);
//function to traverse
function traverse(node) {
currentNode = node;
while (currentNode.left) {
displayNodes(currentNode);
parent = currentNode;
currentNode = currentNode.left;
displayNodes(currentNode);
if(parent.right!=null){
displayNodes(parent.right);
}
}
}
//function that displays the left and right node of a node
function displayNodes(node) {
if (node.left != null) {
console.log(node.left.value);
}
if (node.right != null) {
console.log(node.right.value);
}
}
Ich bin nicht in der Lage, eine Funktion zu implementieren, die mit einer großen Anzahl von Daten skalieren konnte. Ich bin mir nicht sicher, ob eine rekursive Methode besser wäre oder eine while-Schleife. Wie kann ich die Funktion implementieren? Ich weiß, dass die Funktion zu unerwartetem Verhalten führt. Welche Korrektur soll ich machen?
Was hältst du davon, dass es nicht auf eine große Datenmenge skaliert wird? –