Construct a Perfect Binary Tree from Preorder Traversal | Structure of the tree ; Function to create a new node with the value val ; Return the newly created node ; Function to create the Perfect Binary Tree ; If preStart > preEnd return NULL ; Initialize root as pre [ preStart ] ; If the only node is left , then return node ; Parameters for further recursion ; Recursive Call to build the subtree of root node ; Return the created root ; Function to build Perfect Binary Tree ; Function to print the Inorder of the given Tree ; Base Case ; Left Recursive Call ; Print the data ; Right Recursive Call ; Driver Code ; Function Call ; Print Inorder Traversal
class Node { constructor ( val ) { this . left = null ; this . right = null ; this . data = val ; } } function getNewNode ( val ) { let newNode = new Node ( val ) ; return newNode ; } function buildPerfectBT_helper ( preStart , preEnd , pre ) { if ( preStart > preEnd ) return null ; let root = getNewNode ( pre [ preStart ] ) ; if ( preStart == preEnd ) return root ; let leftPreStart = preStart + 1 ; let rightPreStart = leftPreStart + parseInt ( ( preEnd - leftPreStart + 1 ) / 2 ) ; let leftPreEnd = rightPreStart - 1 ; let rightPreEnd = preEnd ; root . left = buildPerfectBT_helper ( leftPreStart , leftPreEnd , pre ) ; root . right = buildPerfectBT_helper ( rightPreStart , rightPreEnd , pre ) ; return root ; } function buildPerfectBT ( pre , size ) { return buildPerfectBT_helper ( 0 , size - 1 , pre ) ; } function printInorder ( root ) { if ( root == null ) return ; printInorder ( root . left ) ; document . write ( root . data + " " ) ; printInorder ( root . right ) ; } let pre = [ 1 , 2 , 4 , 5 , 3 , 6 , 7 ] ; let N = pre . length ; let root = buildPerfectBT ( pre , N ) ; document . write ( " " ) ; printInorder ( root ) ;