[英]using recursion to print out values of a BST - javascript
I'm trying to understand recursion better in Javascript with this code for a BST. 我试图通过BST的此代码更好地理解Javascript中的递归。 I can print out a BST's values with two methods using recursion, but I can't figure out how to do it all in one method.
我可以使用递归的两种方法打印出BST的值,但是我无法弄清楚如何在一种方法中完成所有操作。
how can I combine 我该如何结合
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); }
into one function? 成一个功能? I've been trying
我一直在尝试
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); } }
What about using a second argument isRoot
with it's default value set to true
? 使用第二个参数
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);
}
}
http://jsfiddle.net/fez1jtsx/ http://jsfiddle.net/fez1jtsx/
This makes tree.sameFunction()
equivalent to calling tree.depthFirstTraversal()
这使得
tree.sameFunction()
等效于调用tree.depthFirstTraversal()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.