这是一个 JavaScript 实现,它伪造了您要求的广度优先遍历的输出,但使用深度优先递归。我将每个深度的节点值存储在一个数组内,一个哈希值内。如果一个级别已经存在(我们有碰撞),那么我们只需推送到该级别的数组。您也可以使用数组而不是 JavaScript 对象,因为我们的级别是数字的并且可以用作数组索引。您可以返回节点、值、转换为链接列表或任何您想要的。为了简单起见,我只是返回值。
BinarySearchTree.prototype.breadthFirstRec = function() {
var levels = {};
var traverse = function(current, depth) {
if (!current) return null;
if (!levels[depth]) levels[depth] = [current.value];
else levels[depth].push(current.value);
traverse(current.left, depth + 1);
traverse(current.right, depth + 1);
};
traverse(this.root, 0);
return levels;
};
var bst = new BinarySearchTree();
bst.add(20, 22, 8, 4, 12, 10, 14, 24);
console.log('Recursive Breadth First: ', bst.breadthFirstRec());
/*Recursive Breadth First:
{ '0': [ 20 ],
'1': [ 8, 22 ],
'2': [ 4, 12, 24 ],
'3': [ 10, 14 ] } */
这是一个使用迭代方法的实际广度优先遍历示例,在 JavaScript 中,以防有人感兴趣。 JavaScript 规则!
BinarySearchTree.prototype.breadthFirst = function() {
var result = '',
queue = [],
current = this.root;
if (!current) return null;
queue.push(current);
while (current = queue.shift()) {
result += current.value + ' ';
current.left && queue.push(current.left);
current.right && queue.push(current.right);
}
return result;
};
console.log('Breadth First: ', bst.breadthFirst());
//Breadth First: 20 8 22 4 12 24 10 14