Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
使用快慢两个指针找到单链表的中间节点,作为BST的根,将左右两个单链表断开后分别递归地建立为其左右子树。
注意递归边界:单链表为空和只有一个元素时特殊处理一下。
/**
* 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)
return NULL;
if(!head->next)
return new TreeNode(head->val);
ListNode* fast = head;
ListNode* slow = head;
ListNode* prev = NULL;
while(fast&&fast->next){
fast = fast->next->next;
prev = slow;
slow = slow->next;
}
TreeNode* root = new TreeNode(slow->val);
prev->next = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
};