题目描述
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:通过快慢指针找到中间结点,将中间结点插入到二叉搜索树中,然后从中间将有序单链表拆成两部分,前半部分递归为左子树,后半部分递归为右子树。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* 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){
return nullptr;
}
if(!head->next){
return new TreeNode(head->val);
}
ListNode* fast = head;
ListNode* slow = head;
ListNode* pre = head;
while(fast && fast->next){
fast = fast->next->next;
pre = slow;
slow = slow->next;
}
TreeNode* root = new TreeNode(slow->val);
pre->next = nullptr;
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
};