Construct Tree from given Inorder and Preorder traversals | Python3 program to construct a tree using inorder and preorder traversal ; Function to build tree using given traversal ; Function to prtree in_t Inorder ; first recur on left child ; then prthe data of node ; now recur on right child ; Driver code
class TreeNode : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . val = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT s = set ( ) NEW_LINE st = [ ] NEW_LINE def buildTree ( preorder , inorder , n ) : NEW_LINE INDENT root = None ; NEW_LINE pre = 0 NEW_LINE in_t = 0 NEW_LINE while pre < n : NEW_LINE INDENT node = None ; NEW_LINE while True : NEW_LINE INDENT node = TreeNode ( preorder [ pre ] ) NEW_LINE if ( root == None ) : NEW_LINE INDENT root = node ; NEW_LINE DEDENT if ( len ( st ) > 0 ) : NEW_LINE INDENT if ( st [ - 1 ] in s ) : NEW_LINE INDENT s . discard ( st [ - 1 ] ) ; NEW_LINE st [ - 1 ] . right = node ; NEW_LINE st . pop ( ) ; NEW_LINE DEDENT else : NEW_LINE INDENT st [ - 1 ] . left = node ; NEW_LINE DEDENT DEDENT st . append ( node ) ; NEW_LINE if pre >= n or preorder [ pre ] == inorder [ in_t ] : NEW_LINE INDENT pre += 1 NEW_LINE break NEW_LINE DEDENT pre += 1 NEW_LINE DEDENT node = None ; NEW_LINE while ( len ( st ) > 0 and in_t < n and st [ - 1 ] . val == inorder [ in_t ] ) : NEW_LINE INDENT node = st [ - 1 ] ; NEW_LINE st . pop ( ) ; NEW_LINE in_t += 1 NEW_LINE DEDENT if ( node != None ) : NEW_LINE INDENT s . add ( node ) ; NEW_LINE st . append ( node ) ; NEW_LINE DEDENT DEDENT return root ; NEW_LINE DEDENT def printInorder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return ; NEW_LINE DEDENT printInorder ( node . left ) ; NEW_LINE print ( node . val , end = " ▁ " ) ; NEW_LINE printInorder ( node . right ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT in_t = [ 9 , 8 , 4 , 2 , 10 , 5 , 10 , 1 , 6 , 3 , 13 , 12 , 7 ] NEW_LINE pre = [ 1 , 2 , 4 , 8 , 9 , 5 , 10 , 10 , 3 , 6 , 7 , 12 , 13 ] NEW_LINE l = len ( in_t ) NEW_LINE root = buildTree ( pre , in_t , l ) ; NEW_LINE printInorder ( root ) ; NEW_LINE DEDENT