> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/109.-convert-sorted-list-to-binary-search-tree.md).

# 109. Convert Sorted List to Binary Search Tree

## 1.問題

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

![](/files/-LKRT2aU3ufuJFTmWr2y)

## 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

![](/files/-LKRTl5KKk7gEd5jOilm)
