Description:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
将链表转化为二叉搜索树,并且要求高度是平衡的
Solution:
1、因为要求高度是平衡的,那么我们要找出链表中中间值
2、如何找出中间值,这里同样是利用快慢两个指针,快的一次走2步,慢的一次走1步,这样当快指针走完时,慢指针所在的位置就会是在中间节点,这里设定当节点数为偶数时,中间节点为中间的2个节点的左节点。
3、得到中间节点后,就可知中间节点为根,左部分为左子树,右部分为右子树,递归下去即可。
4、这里在递归左子树部分时,注意结束的标志,如果以到NULL为结束标志的话,那么需要先预处理将左部分的最后一个节点的next由mid改为NULL;当然如果在不改变原链表的情况下,就只能将开始和结束下标作为函数参数传进去。
Code:
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head==NULL)
return NULL;
ListNode* slow=head;
ListNode* fast=head;
ListNode* preslow=NULL;
while(fast->next&&fast->next->next)
{
preslow=slow;
slow=slow->next;
fast=fast->next->next;
}//find mid node
TreeNode* root=new TreeNode(slow->val);
if(preslow)
{
preslow->next=NULL;//make it NULL to have a stop flag
root->left=sortedListToBST(head);
}
else
root->left=NULL;
root->right=sortedListToBST(slow->next);
return root;
}
};