我正在尝试使用BST的这段代码更好地理解Javascript中的递归。我可以使用递归的两种方法打印出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);
}
}
答案 0 :(得分:1)
使用第二个参数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()