Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
给出一个单链表,结点是按元素递增的顺序排序,把链表转换成高度平衡的二叉搜索树
解题分析:
由于链表是按节结点的值递增排序的,因此可以使用双指针,一个快一个慢,遍历到中间部分找到中间结点,然后使用分治法的思想,递归对链表的前半部分和后半部门进行建立。要注意递归的边界出口。
代码如下:
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head)
{
return sortedListToBST( head, NULL );
}
private:
TreeNode *sortedListToBST(ListNode *head, ListNode *tail)
{
if( head == tail )
return NULL;
if( head->next == tail ) //
{
TreeNode *root = new TreeNode( head->val );
return root;
}
ListNode *mid = head, *temp = head;
while( temp != tail && temp->next != tail ) // 寻找中间节点
{
mid = mid->next;
temp = temp->next->next;
}
TreeNode *root = new TreeNode( mid->val );
root->left = sortedListToBST( head, mid );
root->right = sortedListToBST( mid->next, tail );
return root;
}
};