Function to build tree using given traversal
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