GeeksforGeeks » Trees specific questions

Convert a Sorterd Linked list in to a balanced Binary Search Tree

(5 posts)
[closed]
  • Started 1 year ago by Phani Kiran Hemadri
  • Latest reply from kartik
  1. Phani Kiran Hemadri
    guest
    Posted 1 year ago #

    Given a Sorted Linked List.
    Convert it in to any balanced Binary Search Tree.
    Validate that the output is really a balanced tree.

    Ex:
    Input

    1 --> 2 --> 3 --> 4--> 5 --> NULL

    Output

                                            3
                                      /         \
                                 1                 5
                                   \              /
                                     2          4
    
  2. kartik
    Moderator
    Posted 1 year ago #

    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
     /
    2
    

    Pick middle of right half, i.e., 6 and make it right child of 4

        4
     /     \
    2       6
    

    Recursively follow above steps.

  3. Jatin
    Member
    Posted 1 year ago #

    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).

  4. kartik
    Moderator
    Posted 1 year ago #

    @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.

  5. kartik
    Moderator
    Posted 4 months ago #

    This has been published. See http://www.geeksforgeeks.org/archives/17063


Topic Closed

This topic has been closed to new replies.

RSS feed for this topic