【发布时间】:2017-05-01 16:40:51
【问题描述】:
我有以下在 JavaScript 中实现 BST 树的代码。
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 循环。如何实现该功能?我知道该功能会产生意想不到的行为吗?我应该做哪些更正?
【问题讨论】:
-
它是什么让您认为它无法扩展到大量数据?
标签: javascript data-structures binary-search-tree traversal recursive-datastructures