import java.util.LinkedList;
import java.util.Queue;
/**
* Node Structre
* @author Prateek
*
*/
class Node {
Node left;
int data;
Node right ;
public Node(int val){
this.data=val;
}
return this.data + "";
}
}
/**
* Binary Tree to DLL conversion
* @author Prateek
*/
class BinaryToDLink {
/**
* Binary Tree to DLL (using QUeue)
* @param root
*/
public void changeToDLL(Node root){
if(root==null)
return;
Queue<Node> queue= new LinkedList<Node>();
queue.offer(root); //push 1st element
Node parent =null;
Node child =null;
while(!queue.isEmpty()){
Node popedItem = queue.poll();
child = popedItem;
if(child.left!=null)
queue.offer(child.left) ;
if(child.right!=null)
queue.offer(child.right) ;
child.right = queue.peek();
child.left = parent;
parent = child;
}
printList(parent) ;
}
public void printList(Node last){
Node temp=last;
while(temp!=null){
System.
out.
print(" <---" +temp.
data); temp=temp.left;
}
}
public static void main
(String[] args
) { Node root = new Node(1) ;
root.left= new Node(2) ;
root.right= new Node(3) ;
root.left.left= new Node(4) ;
root.left.right= new Node(5) ;
BinaryToDLink obj= new BinaryToDLink();
obj.changeToDLL(root);
}
}
CmltcG9ydCBqYXZhLnV0aWwuTGlua2VkTGlzdDsKaW1wb3J0IGphdmEudXRpbC5RdWV1ZTsKLyoqCiAqIE5vZGUgU3RydWN0cmUKICogQGF1dGhvciBQcmF0ZWVrCiAqCiAqLwpjbGFzcyBOb2RlIHsKCU5vZGUgbGVmdDsKCWludCBkYXRhOwoJTm9kZSByaWdodCA7CgkKCXB1YmxpYyBOb2RlKGludCB2YWwpewoJCXRoaXMuZGF0YT12YWw7Cgl9CgkKCXB1YmxpYyBTdHJpbmcgdG9TdHJpbmcoKXsKCQlyZXR1cm4gdGhpcy5kYXRhICsgIiI7Cgl9Cn0KCi8qKgogKiBCaW5hcnkgVHJlZSB0byBETEwgY29udmVyc2lvbgogKiBAYXV0aG9yIFByYXRlZWsKICovCiBjbGFzcyBCaW5hcnlUb0RMaW5rIHsKCgkvKioKCSAqIEJpbmFyeSBUcmVlIHRvIERMTCAodXNpbmcgUVVldWUpCgkgKiBAcGFyYW0gcm9vdAoJICovCglwdWJsaWMgdm9pZCBjaGFuZ2VUb0RMTChOb2RlIHJvb3QpewogICAgICAgICAgICAKICAgICAgICAgICAgICBpZihyb290PT1udWxsKQogICAgICAgICAgICAJICByZXR1cm47CiAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgUXVldWU8Tm9kZT4gcXVldWU9IG5ldyBMaW5rZWRMaXN0PE5vZGU+KCk7CiAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgcXVldWUub2ZmZXIocm9vdCk7ICAvL3B1c2ggMXN0IGVsZW1lbnQKICAgICAgICAgICAgICAKICAgICAgICAgICAgICBOb2RlIHBhcmVudCA9bnVsbDsKICAgICAgICAgICAgICBOb2RlIGNoaWxkID1udWxsOwogICAgICAgICAgICAgIAogICAgICAgICAgICAgIHdoaWxlKCFxdWV1ZS5pc0VtcHR5KCkpewogICAgICAgICAgICAJICAKICAgICAgICAgICAgCSAgTm9kZSBwb3BlZEl0ZW0gPSBxdWV1ZS5wb2xsKCk7CiAgICAgICAgICAgIAkgIGNoaWxkID0gcG9wZWRJdGVtOwogICAgICAgICAgICAJICAKICAgICAgICAgICAgCWlmKGNoaWxkLmxlZnQhPW51bGwpCiAgICAgICAgICAgIAkgcXVldWUub2ZmZXIoY2hpbGQubGVmdCkgOwogICAgICAgICAgICAJaWYoY2hpbGQucmlnaHQhPW51bGwpIAogICAgICAgICAgICAJcXVldWUub2ZmZXIoY2hpbGQucmlnaHQpIDsKICAgICAgICAgICAgCSAKICAgICAgICAgICAgCSBjaGlsZC5yaWdodCA9IHF1ZXVlLnBlZWsoKTsKICAgICAgICAgICAgCQogICAgICAgICAgICAJIGNoaWxkLmxlZnQgPSBwYXJlbnQ7CiAgICAgICAgICAgIAkgcGFyZW50ID0gY2hpbGQ7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIAogICAgICAgICAgICAgIHByaW50TGlzdChwYXJlbnQpIDsKCX0KCQoJcHVibGljIHZvaWQgcHJpbn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