> 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, 轉換成高度平衡樹

![](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)
