# Binary Search Tree from Sorted Array

Given a sorted array, write an algorithm to create a binary search tree with minimal height

{% tabs %}
{% tab title="Scala" %}

```scala
import scala.collection.mutable

trait BTree

object Empty extends BTree

case class Node(var value: Int, var left: BTree = Empty, var right: BTree = Empty) extends BTree

def printBTree(root: BTree): Unit = {
  val queue = mutable.Queue[(BTree, Int)]((root, 0))
  var prev = -1
  while (!queue.isEmpty) {
    val (node, level) = queue.dequeue()
    node match {
      case n: Node => {
        if (level != prev) {
          print("\n#")
          prev = level
        }
        print(n.value)
        queue.enqueue((n.left, level + 1))
        queue.enqueue((n.right, level + 1))
      }
      case _ =>
    }
  }
}

/**
  * 4.3
  *
  * @param arr
  * @return
  */
def buildTree(arr: Array[Int]): BTree = {
  buildTreeRange(arr, 0, arr.length - 1)
}

def buildTreeRange(arr: Array[Int], start: Int, end: Int): BTree = {
  if (arr.length == 0 || end < start) Empty
  else {
    val mid: Int = (end + start) / 2
    val node: Node = Node(arr(mid))
    node.left = buildTreeRange(arr, start, mid - 1)
    node.right = buildTreeRange(arr, mid + 1, end)
    node
  }
}

val root = buildTree(Array(1, 2, 3, 4))
printBTree(root)
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.bernardw.com/problems/binary-search-tree-from-sorted-array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
