在Javascript中,我试图更好地理解BST的这段代码中的递归。我可以使用递归用两个方法打印出BST的值,但是我不知道如何在一个方法中完成所有的工作。
我怎么才能结合
BinarySearchTree.prototype.dfs = function(node) {
if (node) {
console.log(node.val);
this.dfs(node.left);
this.dfs(node.right);
}
}
BinarySearchTree.prototype.depthFirstTraversal = function() {
let current = this.root;
this.dfs(current);
}
变成一个函数?我一直在努力
BinarySearchTree.prototype.sameFunction = function(node = null) {
// if node is null use this.root
let current = node || this.root;
if (current) {
console.log(current.val);
this.sameFunction(current.left);
this.sameFunction(current.right);
}
}
发布于 2018-10-25 18:17:02
如果使用第二个参数isRoot
并将其默认值设置为true
如何?
BinarySearchTree.prototype.sameFunction = function(node = null, isRoot = true) {
let current = isRoot ? this.root : node;
if (current) {
console.log(current.val);
this.sameFunction(current.left, false);
this.sameFunction(current.right, false);
}
}
这使得tree.sameFunction()
等同于调用tree.depthFirstTraversal()
。
https://stackoverflow.com/questions/52995129
复制相似问题