FastPrepBuild a Tree from Preorder and Inorder Traversals
Problems/Build a Tree from Preorder and Inorder Traversals

Build a Tree from Preorder and Inorder Traversals

StackAdapt logoStackAdapt● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report establishes the task identity and central capability. This practice contract supplies only the portable interface, deterministic boundary rules, and output serialization needed for consistent execution.

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

  • Maximum Bananas Delivered by a CamelONSITE INTERVIEW · Seen Sep 2026
  • Reservoir Sampling with Recorded DrawsONSITE INTERVIEW · Seen Sep 2026
  • Running Medians and PercentilesPHONE SCREEN · Seen Aug 2026
All StackAdapt interview questionsSee StackAdapt hiring insights
Saved
class Solution {
    public String[] buildTreeLevelOrder(int[] preorder, int[] inorder) {
      // write your code here
    }
}
Checking account…