MediumArrayHash TableDivide and ConquerTreeBinary Tree

1 approach, code in every language

Problem description

You are given two integer arrays, inorder and postorder. The inorder array records the node values of a binary tree during an inorder traversal (left, root, right), and postorder records them during a postorder traversal (left, right, root).

All values are distinct. Build the binary tree that produces these two traversals and return its root.

Example 1

Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]

Output: [3,9,20,null,null,15,7]

3 is the root because it comes last in postorder. It sits at index 1 in inorder, so [9] is the left subtree and [15,20,7] is the right subtree.

Example 2

Input: inorder = [-1], postorder = [-1]

Output: [-1]

Only one node exists, so the tree is a single root.

Constraints

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorder and postorder consist of unique values.
  • Each value of postorder also appears in inorder.
  • inorder is guaranteed to be the inorder traversal of the tree.
  • postorder is guaranteed to be the postorder traversal of the tree.

After the pattern

Now solve one you haven't seen.

Rebuilding a Rig From Two Readings is our own problem on the technique behind Construct Binary Tree from Inorder 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