有序单链表转换为平衡二叉树。
TreeNode *buildTree(ListNode *&list,int n)
{
if (n == 0)
return NULL;
TreeNode *root = new TreeNode(0);
root->left = buildTree(list,n / 2);
root->val = list->val;
list = list->next;
root->right = buildTree(list,n - n / 2 - 1);
return root;
}
TreeNode* sortedListToBST(ListNode* head)
{
int size = 0;
ListNode *p = head;
while (p)
{
size++;
p = p->next;
}
p = head;
ListNode *list = head;
return buildTree(list,size);
}