FastPrepBuild a Tree from Preorder and Inorder Traversals

Build a Tree from Preorder and Inorder Traversals

StackAdapt logoStackAdapt● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Reconstruct the unique binary tree described by the preorder and inorder traversals. All values are distinct.

Return the constructed tree in level order as strings. Use # for a missing child and remove all trailing # markers. Return an empty array for an empty tree.

Function

buildTreeLevelOrder(preorder: int[], inorder: int[]) → String[]

Examples

Example 1

preorder = [3,9,20,15,7]inorder = [9,3,15,20,7]return = ["3","9","20","#","#","15","7"]

The root is 3, with leaf 9 and a right subtree rooted at 20.

Example 2

preorder = []inorder = []return = []

Empty traversals construct an empty tree.

Constraints

  • 0 <= preorder.length <= 10000.
  • Both arrays have equal length, contain the same distinct values, and describe a valid tree.

More StackAdapt problems

See StackAdapt hiring insights
public String[] buildTreeLevelOrder(int[] preorder, int[] inorder) {
  // write your code here
}
preorder[3,9,20,15,7]
inorder[9,3,15,20,7]
expected["3", "9", "20", "#", "#", "15", "7"]
Checking account…