Convert Sorted List to Binary Search Tree
Total Accepted: 21420 Total Submissions: 78476 My SubmissionsGiven a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
题意:把有序单链表转换为二叉查找树
思路:
用链表中心作为当作二叉树的根,
链表的前半段作为左子树、后半段作为右子树。
可用递归实现
复杂度:时间O(n* log n),空间O(log n)
TreeNode * dfs(ListNode *head, int size){
if(size <= 0) return NULL;
if(size == 1) return new TreeNode(head->val);
ListNode *cur = head;
for(int i = 0; i < size/2; ++i){
cur = cur->next;
}
TreeNode *root = new TreeNode(cur->val);
root->left = dfs(head, size/2);
root->right = dfs(cur->next, size - size/2 - 1 );
return root;
}
TreeNode *sortedListToBST(ListNode *head) {
ListNode *cur = head;
int size = 0;
while(cur){
++size;
cur = cur->next;
}
return dfs(head, size);
}