You can solve it with BFS and DFS algorithms. I think DFS suits better, since it does not need additional space.
Here is a solution, written on java.
Class that represents doubly linked list:
public static class DLLNode {
public E value;
public DLLNode next;
public DLLNode previous;
public DLLNode(E value) {
this.value = value;
}
public void linkNext(DLLNode n) {
next = n;
n.previous = this;
}
}
Class that represents tree (binary in this case):
public static class TreeNode {
public E value;
public TreeNode left;
public TreeNode right;
public TreeNode(E value) {
this.value = value;
}
}
and method that converts tree to dll and return tail of a list:
public static DLLNode convertToDLLDFS(TreeNode root) {
if (root == null) {
return null;
}
return convertToDLLDFS(root, null);
}
private static DLLNode convertToDLLDFS(TreeNode root, DLLNode currentTail) {
DLLNode tail = new DLLNode(root.value);
if (currentTail != null) {
currentTail.linkNext(tail);
}
if (root.left != null) tail = convertToDLLDFS(root.left, tail);
if (root.right != null) tail = convertToDLLDFS(root.right, tail);
return tail;
}
Time complexity is O(n), since each tree node visited once, space complexity is O(1) since there is no additional space required.