GeeksforGeeks » Trees specific questions
Convert a Sorterd Linked list in to a balanced Binary Search Tree
(5 posts)-
Given a Sorted Linked List.
Convert it in to any balanced Binary Search Tree.
Validate that the output is really a balanced tree.Ex:
Input1 --> 2 --> 3 --> 4--> 5 --> NULL
Output
3 / \ 1 5 \ / 2 4 -
1) Get the Middle of the linked list and make it root. 2) Recursively do same for left half and right half. a) Get the middle of left half and make it left child of the root created in step 1. b) Get the middle of right half and make it right child of the root created in step 1.The algo can be better understood by following example:
1 --> 2 --> 3 --> 4--> 5 -->6-->7--> NULL
Pick middle, i.e., 4 and make it root
4
Pick middle of left half, i.e., 2 and make it left child of 4
4 / 2Pick middle of right half, i.e., 6 and make it right child of 4
4 / \ 2 6Recursively follow above steps.
-
The solution looks OK, though the time complexity of this solution can be an issue.
Since we are given a sorted linked list, hence to reach at particular "mid point node" we need to traverse it starting the head node. Time complexity for traversal of a particular node is O(n), hence time complexity of traversal alone for all n nodes will be O(n^2). -
@Jatin,
Time complexity would be O(nLogm). See, the recurrence relation of this solution is same as merge sort.
T(n) = 2*T(n/2) + O(n)
2*T(n/2) --------------> For two sublists
O(n) -------------------> For splitting the list in two halves and inserting in the BST. -
This has been published. See http://www.geeksforgeeks.org/archives/17063
Topic Closed
This topic has been closed to new replies.