Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
题意;将排序链表转换成平衡二叉树;
每次取中间节点,自然就是平衡二叉树了;
思路:自顶向下递归解决,先找到中间节点作为根节点,然后递归左右两部分,所以我们先需要连找到中间节点,对于单链表来说,
必须要遍历一遍,可以使用快慢指针加速查找速度;
[cpp] view plain copy
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head)
{
if (head==NULL)
{
return NULL;
}
//用快慢指针来找中间节点
ListNode* slow = head;
ListNode* fast = head;
ListNode* preSlow = NULL;
while (fast!=NULL && fast->next!=NULL)
{
preSlow = slow;
slow = slow->next;
fast = fast->next->next;
}
TreeNode* mid = new TreeNode(slow->val);
//分别递归左右部分
if (preSlow!=NULL)
{
preSlow->next = NULL;
mid->left = sortedListToBST(head);
}
if (slow->next!=NULL)
{
mid->right = sortedListToBST(slow->next);
}
return mid;
}
};