FunctionRacerProblemsRace

Build Tree from Preorder and Inorder

MediumTreesPython, JavaScript, TypeScript, Java, C++

You get the lists preorder and inorder, two traversals of one binary tree with distinct values. Rebuild the tree and return its root. (The first item of the preorder list is the root; find it in the inorder list to see which values lie in the left and right subtrees.)

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

preorder [3,9,20,15,7]
inorder [9,3,15,20,7]
returns [3,9,20,null,null,15,7]

Root 3; left subtree is just 9; right subtree is 20 with children 15 and 7.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems