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 *listToBST(ListNode *&head, int first, int last) {
if (first > last)
return NULL;
int mid = (first+last)/2;
TreeNode *node = new TreeNode(-1);
node->left = listToBST(head, first, mid-1);
node->val = head->val;
head = head->next;
node->right = listToBST(head, mid+1, last);
return node;
}
TreeNode *sortedListToBST(ListNode *head) {
if (head==NULL)
return NULL;
int length = 0;
ListNode *tmp = head;
while (head!=NULL) {
length++;
head = head->next;
}
return listToBST(tmp, 0, length-1);
}
};