33. 二叉树的层序遍历

RT

来个 Scala 版

  case class TreeNode[T](value: T, left: TreeNode[T] = null, right: TreeNode[T] = null)

  def levelOrderTraversal[T](tree: TreeNode[T]): Seq[Seq[T]] = {
    val queue = mutable.Queue[TreeNode[T]](tree)
    var results = Vector[Seq[T]]()
    while (queue.nonEmpty) {
      results :+= queue.indices.map { _ =>
        val node = queue.dequeue()
        if (node.left != null) queue.enqueue(node.left)
        if (node.right != null) queue.enqueue(node.right)
        node.value
      }
    }
    results
  }