Extract Leaves of a Binary Tree in a Doubly Linked List | A binary tree node ; Main function which extracts all leaves from given Binary Tree . The function returns new root of Binary Tree ( Note thatroot may change if Binary Tree has only one node ) . The function also sets * head_ref as head of doubly linked list . left pointer of tree is used as prev in DLL and right pointer is used as next ; Utility function for printing tree in InOrder ; Utility function for printing double linked list . ; Driver program to test above function
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def extractLeafList ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . left is None and root . right is None : NEW_LINE INDENT root . right = extractLeafList . head NEW_LINE if extractLeafList . head is not None : NEW_LINE INDENT extractLeafList . head . left = root NEW_LINE DEDENT extractLeafList . head = root NEW_LINE return None NEW_LINE DEDENT root . right = extractLeafList ( root . right ) NEW_LINE root . left = extractLeafList ( root . left ) NEW_LINE return root NEW_LINE DEDENT def printInorder ( root ) : NEW_LINE INDENT if root is not None : NEW_LINE INDENT printInorder ( root . left ) NEW_LINE print root . data , NEW_LINE printInorder ( root . right ) NEW_LINE DEDENT DEDENT def printList ( head ) : NEW_LINE INDENT while ( head ) : NEW_LINE INDENT if head . data is not None : NEW_LINE INDENT print head . data , NEW_LINE DEDENT head = head . right NEW_LINE DEDENT DEDENT extractLeafList . head = Node ( None ) NEW_LINE root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . right = Node ( 6 ) NEW_LINE root . left . left . left = Node ( 7 ) NEW_LINE root . left . left . right = Node ( 8 ) NEW_LINE root . right . right . left = Node ( 9 ) NEW_LINE root . right . right . right = Node ( 10 ) NEW_LINE print " Inorder ▁ traversal ▁ of ▁ given ▁ tree ▁ is : " NEW_LINE printInorder ( root ) NEW_LINE root = extractLeafList ( root ) NEW_LINE print   " NEW_LINE Extract Double Linked List is : " NEW_LINE printList ( extractLeafList . head ) NEW_LINE print   " NEW_LINE Inorder traversal of modified tree is : " NEW_LINE printInorder ( root ) NEW_LINE