Convert sorted list to binary search tree total accepted: 21420 total submissions: 78476my submissions
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Change an ordered single-chain table to a binary search tree
Ideas:
Using the chain table center as the root of a binary tree,
The first half of the linked list is the left subtree and the second half is the right subtree.
Recursive Implementation
Complexity: time O (N * log n), Space 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);}
Leetcode DFS convert sorted list to Binary Search Tree