我试图用这段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);
}
}
http://jsfiddle.net/rj2tyd4L/
使用默认值设置为true
的第二个参数isRoot
怎么样?
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);
}
}
http://jsfiddle.net/fez1jtsx/
这使得tree.sameFunction()
等同于调用tree.depthFirstTraversal()