使用递归打印出BST的值-javascript

时间:2018-10-25 17:37:05

标签: javascript

我正在尝试使用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/

1 个答案:

答案 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);
  }
}

http://jsfiddle.net/fez1jtsx/

这使tree.sameFunction()等同于调用tree.depthFirstTraversal()