题目:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
由排序链表构造二叉树。根据数组构造二叉树的思想,想到对链表不断二分的方式完成功能。
TreeNode *sortedListToBST(ListNode *head)
{
TreeNode *root=NULL;
if(!head) return root;
if(!head->next) return root=new TreeNode(head->val);
ListNode *p=head, *q=head, *pre=NULL;
while(q&&q->next!=NULL) //下面是链表二分过程
{
q=q->next->next;
pre=p; //pre是用来后面断开链表的
p=p->next; //步长不同
}
pre->next=NULL; //断开链表
root=new TreeNode(p->val);
p=p->next; //构造了根节点,不能再用了
root->left=sortedListToBST(head);
root->right=sortedListToBST(p);
return root;
}