Meta Interview Question

Convert a tree to a doubly linked list.

Interview Answers

Anonymous

May 10, 2015

Why did you assume this is a binary tree?

2

Anonymous

May 6, 2015

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.

Anonymous

May 8, 2015

DFS seems like it doesn't need additional space because it's using the stack as the additional space