题目:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
程序:
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
return BST(head,NULL);
}
TreeNode *BST(ListNode *head,ListNode *tail)
{
if(head == tail)
return NULL;
ListNode *s = head;
ListNode *f = head;
while(f!=tail && f->next!=tail)
{
s = s->next;
f = f->next->next;
}
TreeNode *root = new TreeNode(s->val);
root->left = BST(head,s);
root->right = BST(s->next,tail);
return root;
}
};