Convert a given Binary Tree to Doubly Linked List | Set 3 | A binary tree node has data , left pointers and right pointers ; head -- > Pointer to head node of created doubly linked list ; A simple recursive function to convert a given Binary tree to Doubly Linked List root -- > Root of Binary Tree ; Base case ; Initialize previously visited node as NULL . This is so that the same value is accessible in all recursive calls ; Recursively convert left subtree ; Now convert this node ; Finally convert right subtree ; Function to print nodes in a given doubly linked list ; Let us create the tree as shown in above diagram ; convert to DLL ; Print the converted List
class Node { constructor ( val ) { this . data = val ; this . left = null ; this . right = null ; } } var root ; var head ; function BinaryTree2DoubleLinkedList ( root ) { if ( root == null ) return ; var prev = null ; BinaryTree2DoubleLinkedList ( root . left ) ; if ( prev == null ) head = root ; else { root . left = prev ; prev . right = root ; } prev = root ; BinaryTree2DoubleLinkedList ( root . right ) ; } function printList ( node ) { while ( node != null ) { document . write ( node . data + " " ) ; node = node . right ; } } 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 ) ; BinaryTree2DoubleLinkedList ( root ) ; printList ( head ) ;