您的位置:首页 > 其它

Leetcode #109 Convert Sorted List to Binary Search Tree

2015-08-08 16:43 555 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Difficulty:Medium

TreeNode* sortedListToBST(ListNode* head) {
TreeNode* root;
if(head==NULL)
return NULL;
if(head->next==NULL)
{
root = new TreeNode(head->val);
return root;
}
ListNode* p = head;
ListNode* pNext = p;
ListNode* pre = p;
while(pNext->next!=NULL&&pNext->next->next!=NULL){
pre = p;
p = p->next;
pNext = pNext->next->next;
}
root = new TreeNode(p->val);
p = p->next;
pre->next = NULL;
if(root->val == head->val)
head = NULL;
root->left = sortedListToBST(head);
root->right = sortedListToBST(p);

return root;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: