Function to build tree using given traversal
function buildTree ( preorder , inorder ) { let root = null ; for ( let pre = 0 , In = 0 ; pre < preorder . length ; ) { let node = null ; do { node = new TreeNode ( preorder [ pre ] ) ; if ( root == null ) { root = node ; } if ( stack . length != 0 ) { if ( set . has ( stack [ stack . length - 1 ] ) ) { set . delete ( stack [ stack . length - 1 ] ) ; stack . pop ( ) . right = node ; } else { stack [ stack . length - 1 ] . left = node ; } } stack . push ( node ) ; } while ( preorder [ pre ++ ] != inorder [ In ] && pre < preorder . length ) ; node = null ; while ( stack . length != 0 && In < inorder . length && stack [ stack . length - 1 ] . val == inorder [ In ] ) { node = stack . pop ( ) ; In ++ ; } if ( node != null ) { set . add ( node ) ; stack . push ( node ) ; } } return root ; }