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 . isEmpty ( ) ) { 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 . isEmpty ( ) && in < inorder . length && stack . peek ( ) . val == inorder [ in ] ) { node = stack . pop ( ) ; in ++ ; } if ( node != null ) { set . add ( node ) ; stack . push ( node ) ; } } return root ; }