Algorithm 如何编写一个方法,将二进制搜索树(BST)转换为BST中值的排序列表?

Algorithm 如何编写一个方法,将二进制搜索树(BST)转换为BST中值的排序列表?,algorithm,scala,data-structures,binary-search-tree,Algorithm,Scala,Data Structures,Binary Search Tree,所以我有一个二叉搜索树,需要用BSTtoList方法生成一个列表,但我不确定一般步骤是什么,或者我必须做什么 class BinarySearchTree[A](comparator: (A, A) => Boolean) { var root: BinaryTreeNode[A] = null def search(a: A): BinaryTreeNode[A] = { searchHelper(a, this.root) } def searchHelp

所以我有一个二叉搜索树,需要用BSTtoList方法生成一个列表,但我不确定一般步骤是什么,或者我必须做什么

class BinarySearchTree[A](comparator: (A, A) => Boolean) {

  var root: BinaryTreeNode[A] = null

  def search(a: A): BinaryTreeNode[A] = {
    searchHelper(a, this.root)
  }

  def searchHelper(a: A, node: BinaryTreeNode[A]): BinaryTreeNode[A] = {
    if(node == null){
      null
    }else if(comparator(a, node.value)){
      searchHelper(a, node.left)
    }else if(comparator(node.value, a)){
      searchHelper(a, node.right)
    }else{
      node
    }
  }


  def BSTtoList: List[A] = {
    var sortedList = List()
    if (root.left != null) {
      sortedList :+ searchHelper(root.value, root.left).value

    }
    else if (root.right != null){
      sortedList :+ searchHelper(root.value, root.right).value
    }
    sortedList
  }
}

让我们先想想BST是如何工作的。在任何给定的节点上,比如值x,左子树中的所有节点的值都将小于x,而右子树中的所有节点的值都将大于x。因此,要返回以节点x为根的子树的排序列表,您只需返回[sorted list of left subtree]+[x]+[sorted list of right subtree],因此您只需在左、右子树上递归调用BSTtoList,然后返回上述列表。从这里开始,您只需处理在空节点返回空列表的基本情况

上面的算法是O(N^2)时间,有一个更好的解决方案,使用在O(N)时间内运行的尾部递归,伪代码:

def BSTtoList(root, accumulator):
    if root == NULL:
        return accumulator
    else:
        return BSTtoList(root.left_child, [root.value] + BSTtoList(root.right_child, accumulator)

其中,最初使用空列表作为累加器调用BSTtoList。第二种解决方案的工作原理与第一种类似,但通过最小化阵列合并进行了优化(如果使用的语言在列表的前面插入了O(1),则此版本的工作效果最好;如果使用的语言允许在列表的后面插入O(1),则实现会有所不同)。

让我们首先考虑一下BST是如何工作的。在任何给定的节点上,比如值x,左子树中的所有节点的值都将小于x,而右子树中的所有节点的值都将大于x。因此,要返回以节点x为根的子树的排序列表,您只需返回[sorted list of left subtree]+[x]+[sorted list of right subtree],因此您只需在左、右子树上递归调用BSTtoList,然后返回上述列表。从这里开始,您只需处理在空节点返回空列表的基本情况

上面的算法是O(N^2)时间,有一个更好的解决方案,使用在O(N)时间内运行的尾部递归,伪代码:

def BSTtoList(root, accumulator):
    if root == NULL:
        return accumulator
    else:
        return BSTtoList(root.left_child, [root.value] + BSTtoList(root.right_child, accumulator)
其中,最初使用空列表作为累加器调用BSTtoList。第二种解决方案的工作原理与第一种类似,但通过最小化数组合并进行了优化(如果使用的语言在列表的前面插入了O(1),则此版本的工作效果最好;如果使用的语言允许在列表的后面插入O(1),则实现略有不同)