Write a function to convert BST it into a sorted linked list. You have to return the head of LL.

 Convert it into a sorted linked list. You have to return the head of LL

The first and only line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node.   
Output Format:
The first and only line of output prints the elements of sorted linked list.
Constraints:
Time Limit: 1 second
Sample Input 1:
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
Sample Output 1:
2 5 6 7 8 10

Code :
import java.util.*;
public class Solution {

public static LinkedListNode<Integer> constructLinkedList(BinaryTreeNode<Integer> root) {
        ArrayList<Integer> list = new ArrayList<>();
        
        helper(root,list);
        
        Collections.sort(list);
        
        LinkedListNode<Integer> head = null;
        LinkedListNode<Integer> tail = null;
        int i=0;
        while(i<list.size())
        {
            LinkedListNode<Integer> cn = new LinkedListNode<Integer>(list.get(i));
            
            if(head==null)
            {
                head=cn;
                tail = cn;
            }
            else
            {
                tail.next=cn;
                tail=tail.next;
            }
            i++;
        }
        return head;
}
    
    public static void helper(BinaryTreeNode<Integer> root, ArrayList<Integer> list)
    {
        if(root==null)
        {
            return;
        }
        
        list.add(root.data);
        helper(root.left,list);
        helper(root.right,list);

}
}

Post a Comment

0 Comments