# 108. Convert Sorted Array to Binary Search Tree

## 1.問題&#x20;

* 利用給予的序列建構出balanced binary search tree

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LOSWpDeKKzRSEn0doCN%2F-LOSi64xkV33E2pxQi1b%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-10-10%20%E4%B8%8B%E5%8D%887.23.59.png?alt=media\&token=1d9e02af-361a-4720-b488-e12828186175)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 確認題意:  height balanced
* function header, parameter input&#x20;
* 說明想法
  * BST定義為left descents <= n < right descents, 如果用二分法, 將每次的mid作為新的root node, 不僅左右高度相同, 而且滿足BST的定義
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
/**
 * 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.size() == 0) {
            return NULL;
        }
        return buildTree(nums, 0, nums.size() - 1);
    }
private:
    TreeNode* buildTree(vector<int>& nums, int left, int right) {
        if (left > right) {
            return NULL;
        }
        
        int mid = (left + right) / 2;
        TreeNode* node = new TreeNode(nums[mid]);
        node->left = buildTree(nums, left, mid - 1);
        node->right = buildTree(nums, mid + 1, right);
        
        return node;
    }
};
```


---

# 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://jenhsuan.gitbook.io/algorithm/leetcode/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.
