Function to build tree using given traversal
public TreeNode buildTree ( int [ ] preorder , int [ ] inorder ) { TreeNode root = null ; for ( int pre = 0 , iN = 0 ; pre < preorder . Length ; ) { TreeNode node = null ; do { node = new TreeNode ( preorder [ pre ] ) ; if ( root == null ) { root = node ; } if ( stack . Count != 0 ) { if ( set . Contains ( stack . Peek ( ) ) ) { set . Remove ( stack . Peek ( ) ) ; stack . Pop ( ) . right = node ; } else { stack . Peek ( ) . left = node ; } } stack . Push ( node ) ; } while ( preorder [ pre ++ ] != inorder [ iN ] && pre < preorder . Length ) ; node = null ; while ( stack . Count != 0 && iN < inorder . Length && stack . Peek ( ) . val == inorder [ iN ] ) { node = stack . Pop ( ) ; iN ++ ; } if ( node != null ) { set . Add ( node ) ; stack . Push ( node ) ; } } return root ; }