Sorted Linked Listing to Balanced BST


class LinkedList {

 

    

    static LNode head;

     

    

    class LNode

    {

        int information;

        LNode subsequent, prev;

 

        LNode(int d)

        {

            information = d;

            subsequent = prev = null;

        }

    }

     

    

    class TNode

    {

        int information;

        TNode left, proper;

 

        TNode(int d)

        {

            information = d;

            left = proper = null;

        }

    }

 

    

       

    TNode sortedListToBST()

    {

        

        int n = countNodes(head);

 

        

        return sortedListToBSTRecur(n);

    }

 

    

       

       

    TNode sortedListToBSTRecur(int n)

    {

        

        if (n <= 0)

            return null;

 

        

        TNode left = sortedListToBSTRecur(n / 2);

 

        

           

        TNode root = new TNode(head.information);

 

        

        root.left = left;

 

        

           

        head = head.subsequent;

 

        

           

           

        root.proper = sortedListToBSTRecur(n - n / 2 - 1);

 

        return root;

    }

 

    

    

       

    int countNodes(LNode head)

    {

        int rely = 0;

        LNode temp = head;

        whereas (temp != null)

        {

            temp = temp.subsequent;

            rely++;

        }

        return rely;

    }

 

    

       

    void push(int new_data)

    {

        

        LNode new_node = new LNode(new_data);

 

        

           

        new_node.prev = null;

 

        

        new_node.subsequent = head;

 

        

        if (head != null)

            head.prev = new_node;

 

        

        head = new_node;

    }

 

    

    void printList(LNode node)

    {

        whereas (node != null)

        {

            System.out.print(node.information + " ");

            node = node.subsequent;

        }

    }

 

    

    void preOrder(TNode node)

    {

        if (node == null)

            return;

        System.out.print(node.information + " ");

        preOrder(node.left);

        preOrder(node.proper);

    }

 

    

    public static void important(String[] args) {

        LinkedList llist = new LinkedList();

 

        

           

        llist.push(7);

        llist.push(6);

        llist.push(5);

        llist.push(4);

        llist.push(3);

        llist.push(2);

        llist.push(1);

 

        System.out.println("Given Linked Listing ");

        llist.printList(head);

 

        

        TNode root = llist.sortedListToBST();

        System.out.println("");

        System.out.println("Pre-Order Traversal of constructed BST ");

        llist.preOrder(root);

    }

}

 

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles