MediumArrayHash TableDivide and ConquerTreeBinary Tree

1 approach, code in every language

Problem description

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.

After the pattern

Now solve one you haven't seen.

Rebuilding The Inspection Rig is our own problem on the technique behind Construct Binary Tree from Preorder and Postorder Traversal: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free