JavaScriptでBSTツリーを実装する次のコードがあります。幅広い最初の検索バイナリ検索ツリーjavascriptの実装
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);
私は、木の最初の横断を行うことができる関数を実装しようとしています。これはこれまで私が試したことです。
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);
}
}
大量のデータで拡大縮小できる機能を実装できません。私は、トラバースする再帰的メソッドが良いか、whileループを使用するかどうかはわかりません。どのように機能を実装できますか?この関数が予期しない動作をすることはわかっていますか?私はどんな訂正をするべきですか?
大量のデータに拡張されないと思うのはどうでしょうか? –