# 109. Convert Sorted List to Binary Search Tree

## 1.問題

* 給予一個已經排序過的linked list, 轉換成高度平衡樹

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKROWPkLULxdEN48MzT%2F-LKRT2aU3ufuJFTmWr2y%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-21%20%E4%B8%8B%E5%8D%888.31.28.png?alt=media\&token=fa55c09c-6ae3-40f7-a913-51a286a9b0c1)

## 2.想法

* 二分法

## 3.程式碼

```
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * 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* sortedListToBST(ListNode* head) {
        if (head == NULL) {
            return NULL;
        }
        vector<int> nodes;
        ListNode* curr = head;
        while (curr) {
            nodes.push_back(curr->val);
            curr = curr->next;
        }
        return buildTree(nodes, 0, nodes.size() - 1);
    }
private:
    TreeNode* buildTree(vector<int> &nodes, int left, int right){
        if(left > right) {
            return NULL;
        }
        int mid = (left + right) / 2;
        TreeNode* node = new TreeNode(nodes[mid]);
        node->left = buildTree(nodes, left, mid - 1);
        node->right = buildTree(nodes, mid + 1, right);
        return node;
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKROWPkLULxdEN48MzT%2F-LKRTl5KKk7gEd5jOilm%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-21%20%E4%B8%8B%E5%8D%888.34.35.png?alt=media\&token=8be371ed-22c3-40c6-a7c5-b3f1490f27cd)


---

# 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/109.-convert-sorted-list-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.
