代码之家  ›  专栏  ›  技术社区  ›  totalnoob

使用递归打印BST-javascript的值

  •  0
  • totalnoob  · 技术社区  · 6 年前

    我试图用这段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 回复  |  直到 6 年前
        1
  •  1
  •   slider    6 年前

    使用第二个参数怎么样 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()