# 108. Convert Sorted Array to Binary Search Tree

{% hint style="info" %}
Finding medium of a sorted list to be root and add to `root.left` and `root.right` respectively. Use recursive.
{% endhint %}

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

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        # edge case
        if len(nums) == 0:
            return None
        
        root = TreeNode(nums[0])
        if len(nums) == 1:
            return root
        
        # regular case
        root.val = nums[len(nums)//2]
        root.left = self.sortedArrayToBST(nums[:len(nums)//2])
        root.right = self.sortedArrayToBST(nums[len(nums)//2+1:])
        
        return root
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}

Time complexity = $$O(n)$$ , space complexity = $$O(1)$$ because only need to record the root.


---

# 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://r24zeng.gitbook.io/leetcode-notebook/binary-search-and-tree/108.-convert-sorted-array-to-binary-search-tree.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.
