> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/108.convert_sorted_array_to_binary_search_tree.md).

# 108.Convert Sorted Array to Binary Search Tree

**108.Convert Sorted Array to Binary Search Tree**

难度:Easy

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

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

示例:

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

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

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

递归求解，代码如下：

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.empty()) return NULL;
        TreeNode* root = new TreeNode(0);
        int t=nums.size();
        if(t == 1) {
            root->val=nums[0];
            return root;
        }
        if(t==2)
        {
            root->val=nums[1];
            root->left=new TreeNode(nums[0]);
            //cout<<root->val<<endl;
            return root;
        }
        if(t==3)
        {
            root->val=nums[1];
            root->left=new TreeNode(nums[0]);
            root->right=new TreeNode(nums[2]);
            return root;
        }
        t=t/2;
        vector<int>n1(nums.begin(),nums.begin()+t),n2(nums.begin()+t+1,nums.end());
        //cout<<n1.size()<<endl;
       // cout<<n2.size()<<endl;
        root->val=nums[t];
        root->left=sortedArrayToBST(n1);
        root->right=sortedArrayToBST(n2);
        return root;
    }
};
```
