Convert a given Binary Tree to Doubly Linked List

Given a Binary Tree (Bt), convert it to a Doubly Linked List(DLL). The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (left most node in BT) must be head node of the DLL.

class Solution {
    Node last;

    Node bToDLL(Node root) {
        if (root == null)
            return root;
        Node leftEnd = bToDLL(root.left);
        if (last != null) {
            last.right = root;
            root.left = last;
        }
        last = root;
        Node rightEnd = bToDLL(root.right);
        root.right = rightEnd;
        if (rightEnd != null)
            rightEnd.left = root;
        return leftEnd == null ? root : leftEnd;
    }
}

Last updated