Hacktoberfest

Home > Data Structures and Algorithms Questions >:Given a BST, convert it into a sorted linked list. Return the head of LL.

Given a BST, convert it into a sorted linked list. Return the head of LL.


Answer:

Here's a code snippet Given a BST, convert it into a sorted linked list. Return the head of LL.



public static LinkedListNode BSTToSortedLL(BinaryTreeNode root){

  if(root == null){
    return null;
  }
   LinkedListNode head=BSTToSortedLL(root.left);
   LinkedListNode q=new LinkedListNode(root.data);
   LinkedListNode tailS=BSTToSortedLL(root.right);
  if(head==null){
     head=q;
  }
   while(temp.next!=null){
   temp=temp.next;
  }
   q.next=tailS;
   return head;
}