This is very interesting problem. And most of solutions are recursive approach which will cause stack overflow.
The below is my solution, which does in-place and iteratively.
The idea is to in-order traverse the tree and use head pointer referencing the head of the linked list and pre pointers referencing the previous node during traverse.
public static Node isBSTAndTreeToDLL(Node root){
  if(root==null)
   return null;  
  Stack<Node> s = new Stack<Node>();  
  Node head = null;
  Node n = root;
  Node pre = null;
  while(!s.isEmpty() || n!=null){     
   if(n!=null){
    s.push(n);
    n = n.left;
   }
   else{
    Node p = s.pop();    
    //this is the left most node
    if(head == null)
     head = p;    
    if(pre!=null){
     pre.right = p;
     p.left = pre;
    }    
    pre=p;    
    n = p.right;
   }       
  }  
  //handle the last node
  pre.right = head;
  head.left = pre;
  return head;
 }
 
No comments:
Post a Comment