MediumArrayHash TableDivide and ConquerTreeBinary Tree

Construct Binary Tree from Preorder and Postorder Traversal

LeetCode
1 approach, code in all languages

You are given two integer arrays, preorder and postorder, that describe a binary tree with distinct node values. preorder gives the values in preorder traversal order (root, left, right) and postorder gives them in postorder order (left, right, root).

Reconstruct any binary tree whose preorder traversal equals preorder and whose postorder traversal equals postorder. If more than one tree is possible you may return any of them, and it is guaranteed that at least one valid answer exists.

Example 1

Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]

Output: [1,2,3,4,5,6,7]

1 is the root. 2, the next preorder value, roots the left subtree; it appears at index 2 in postorder, so [4,5,2] is the left block and [6,7,3] is the right block.

Example 2

Input: preorder = [1], postorder = [1]

Output: [1]

A single node is returned as the root.

Constraints

  • 1 <= preorder.length <= 30
  • preorder.length == postorder.length
  • 1 <= preorder[i], postorder[i] <= preorder.length
  • preorder and postorder consist of distinct values.
  • Both preorder and postorder are valid traversals of the same binary tree.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now