# \[108]\[简单]\[DFS]\[二分] 将有序数组转换为二叉搜索树

## 题目描述

[108. 将有序数组转换为二叉搜索树](https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/)

将一个按照升序排列的有序数组，转换为一棵高度平衡二叉搜索树。

本题中，一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

```
给定有序数组: [-10,-3,0,5,9],

一个可能的答案是：[0,-3,9,-10,null,5]，它可以表示下面这个高度平衡二叉搜索树：

      0
     / \
   -3   9
   /   /
 -10  5
```

## 解题思路

[将有序数组转换为二叉搜索树](https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/solution/jiang-you-xu-shu-zu-zhuan-huan-wei-er-cha-sou-s-33/)

简单来说, **二叉搜索树的中序遍历是升序序列**. 因此可将数组中间的数作为树的根节点, 左右子数组分别构成根节点的左右子树. 而左右子树的构建方法同上, 因此依据DFS的思路, 使用递归逐步得到各级子树.

注意边界条件, 当`left`大于`right`时, 说明此时构成的树为空树.

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        def get_tree(left, right):
            if left > right:
                return None

            mid = (left + right) // 2
            root = TreeNode(nums[mid])
            root.left = get_tree(left, mid - 1)
            root.right = get_tree(mid + 1, right)
            return root
        return get_tree(0, len(nums) - 1)
```

## 相关题目

* 链表版: [\[109\]\[中等\]\[DFS\] 有序链表转换二叉搜索树](/garnet/suan-fa/shuang-zhi-zhen/109-you-xu-lian-biao-zhuan-huan-er-cha-sou-suo-shu.md)


---

# 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://kerasnoone.gitbook.io/garnet/suan-fa/dfs/108-jiang-you-xu-shu-zu-zhuan-huan-wei-er-cha-sou-suo-shu.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.
