Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Balanced Binary Search Tree from Sorted linked list

Tags:

What's the best way to create a balanced binary search tree from a sorted singly linked list?

like image 956
Timothy Chen Avatar asked Nov 20 '10 21:11

Timothy Chen


People also ask

How do you convert a sorted list to a binary search tree solution?

The idea is to insert nodes in BST in the same order as they appear in Linked List so that the tree can be constructed in O(n) time complexity. We first count the number of nodes in the given Linked List. Let the count be n. After counting nodes, we take left n/2 nodes and recursively construct the left subtree.

Can we apply binary search on sorted linked list?

Binary Search is divide and conquer approach to search an element from the list of sorted element. In Linked List we can do binary search but it has time complexity O(n) that is same as what we have for linear search which makes Binary Search inefficient to use in Linked List.


2 Answers

How about creating nodes bottom-up?

This solution's time complexity is O(N). Detailed explanation in my blog post:

http://www.leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html

Two traversal of the linked list is all we need. First traversal to get the length of the list (which is then passed in as the parameter n into the function), then create nodes by the list's order.

BinaryTree* sortedListToBST(ListNode *& list, int start, int end) {   if (start > end) return NULL;   // same as (start+end)/2, avoids overflow   int mid = start + (end - start) / 2;   BinaryTree *leftChild = sortedListToBST(list, start, mid-1);   BinaryTree *parent = new BinaryTree(list->data);   parent->left = leftChild;   list = list->next;   parent->right = sortedListToBST(list, mid+1, end);   return parent; }  BinaryTree* sortedListToBST(ListNode *head, int n) {   return sortedListToBST(head, 0, n-1); } 
like image 103
1337c0d3r Avatar answered Sep 24 '22 23:09

1337c0d3r


You can't do better than linear time, since you have to at least read all the elements of the list, so you might as well copy the list into an array (linear time) and then construct the tree efficiently in the usual way, i.e. if you had the list [9,12,18,23,24,51,84], then you'd start by making 23 the root, with children 12 and 51, then 9 and 18 become children of 12, and 24 and 84 become children of 51. Overall, should be O(n) if you do it right.

The actual algorithm, for what it's worth, is "take the middle element of the list as the root, and recursively build BSTs for the sub-lists to the left and right of the middle element and attach them below the root".

like image 33
Stuart Golodetz Avatar answered Sep 22 '22 23:09

Stuart Golodetz