我试图通过这段 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);
}
}
最佳答案
使用第二个参数 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()
关于javascript - 使用递归打印 BST 的值 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52995129/