Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
分析:利用链表生成平衡二叉查找数。题目中要求生成平衡树,所以我们每次要取链表中间位置的值作为二叉树的一个根。然后依次从左边链表序列和右边链表序列取中间值来递归生成平衡树。
特别注意如何断开链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* 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==NULL)
return NULL;
if(head->next==NULL)
return new TreeNode(head->val);
ListNode *mid = head->next;
ListNode *pre = head;
int n = (length(head))/2;
while(n>1){
mid = mid->next;
pre = pre ->next;
--n;
}
TreeNode *root = new TreeNode(mid->val);
root->right = sortedListToBST(mid->next);
mid->next = NULL;
pre->next = NULL;
root->left = sortedListToBST(head);
}
int length(ListNode *pre){
int n = 0;
while(pre!=NULL){
++n;
pre=pre->next;
}
return n;
}
};