Binary Tree Extract Nodes to Double Linked List

/**

Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. 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.


Let the following be input binary tree
        1
     /     \
    2       3
   / \       \
  4   5       6
 / \         / \
7   8       9   10


Output:
Doubly Linked List

7<->4<->8<->2<->5<->1<->3<->9<->6<->10

ref: https://www.geeksforgeeks.org/convert-given-binary-tree-doubly-linked-list-set-3/
*/

class Node{
Node left, right;
int val;
Node(int v){
val = v;
left = null;
right = null;
}
}
public class BinaryTreeExtractNodesToDoubleLinkedList{

//head node of the doubly linked list
static Node head;
//a node that represents the previously visited node
static Node prev = null;
//a recursive call
static void treeToDList(Node root){
if(root == null){
return;
}

//recursion on left child
treeToDList(root.left);
//if no previous nodes are set, convert this node
if(prev == null){
head = root;
}else{
root.left = prev;
prev.right = root;
}
prev = root;

//recursion on right child
treeToDList(root.right);
}

static void printList(Node node)
    {
        while (node != null) 
        {
            System.out.print(node.val + " ");
            node = node.right;
        }
    }

// Driver program to test above functions
    public static void main(String[] args) 
    {
        // Let us create the tree as shown in above diagram
        Node root = new Node(10);
        root.left = new Node(12);
        root.right = new Node(15);
        root.left.left = new Node(25);
        root.left.right = new Node(30);
        root.right.left = new Node(36);
 
        // convert to DLL
        treeToDList(root);
         
        // Print the converted List
        printList(head);
 
    }
}

No comments:

Post a Comment