https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
- 先找到链表中间节点的前一个节点(注意建dummy node)
- 存下中间节点,根据中间节点的值new出树的根节点
- 切开链表,分别对中间节点的左半部分和右半部分构造BST,最后将它们连到根节点上。
C++
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if (!head) return NULL;
if (!head->next) return new TreeNode(head->val);
ListNode dummy(0); dummy.next = head;
ListNode *mid_prev = find_mid(&dummy);
ListNode *mid = mid_prev->next;
TreeNode *root = new TreeNode(mid->val);
mid_prev->next = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(mid->next);
return root;
}
ListNode* find_mid(ListNode* head) {
ListNode *slow = head, *fast = head->next;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};