收集数组中的递归函数响应

问题描述 投票:0回答:1

我的简短问题是:如何在数组中收集中间响应/递归函数的输出/方法,然后在其他地方打印该数组?

假设我有一个Node类:

class Node {
  constructor (data) {
    this.data = data
    this.left = null
    this.right = null
    this.parent = null
  }
}

和BST类

class BST {
  constructor () {
    this.root = null
    this.nodeCount = 0
  }
  insert (data) {
    const node = new Node(data)
    this.nodeCount++
    if (this.root == null) {
      this.root = node
    } else {
      this.insertNode(this.root, node)
    }
    return this.search(data)
  }
  insertNode (node, newNode) {
    if (newNode.data < node.data) {
      if (node.left === null) {
        newNode.parent = node
        node.left = newNode
      } else {
        this.insertNode(node.left, newNode)
      }
    } else {
      if (node.right === null) {
        newNode.parent = node
        node.right = newNode
      } else {
        this.insertNode(node.right, newNode)
      }
    }
  }
  inOrder (node) {
    if (node !== null) {
      this.inOrder(node.left)
      console.log(node.data)
      this.inOrder(node.right)
    }
  }
  createTree (bst, arr = []) {
    for (let item of arr) {
      bst.insert(item)
    }
    return bst
  }
}

现在有了这两个类,我可以创建一个二叉树:

const bst = new BST()
const tree = bst.createTree(bst, [15, 25, 10, 7, 22, 17, 13, 5, 9, 27])
const root = tree.getRootNode()

然后遍历:

console.log('Traversing tree (InOrder): ')
bst.inOrder(root)

我想做的是遍历时,我想将所有值压入数组而不是打印它。运行bst.inOrder()的结果是,我将获得一个包含树中所有元素的数组。我怎样才能做到这一点?预先感谢您的帮助。

javascript node.js binary-search-tree
1个回答
0
投票

最后,我找到了解决此问题的方法。以下是执行“顺序深度优先遍历”的方法,该方法为我提供了排序后的数组:

traverse(cb) {
  function dfs(node) {
    if (node === null) return
    dfs(node.left)
    cb(node)
    dfs(node.right)
    return node
   }
   dfs(this.root)
   return this
}
此方法应在BST类中。在将项目插入树中之后(在问题中编写的代码),在main函数中,我必须编写以下代码:

const inOrderData = []
bst.traverse(function (node) {
  inOrderData.push(node.data)
})
console.log("Tree data: ", inOrderData)

因此,基本上,我已经发送了一个回调函数以遍历方法作为参数,并且该回调函数接受一个节点作为参数。然后在main函数中,我只是将node的数据推入数组。

© www.soinside.com 2019 - 2024. All rights reserved.