Convert Sorted List to Binary Search Tree
Oct 3 '12
5768 / 16298
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;
ListNode* t = head;
int len = 0;
while (t != NULL) len++, t = t->next;
return gen(head, 0, len - 1);
}
TreeNode *gen(ListNode* &cur, int start, int end) {
if (start > end) return NULL;
int mid = start + (end -start) / 2;
TreeNode *left = gen(cur, start, mid - 1);
TreeNode *node = new TreeNode(cur->val);
cur = cur->next;
node->left = left;
node->right = gen(cur, mid+1, end);
}
};