MediumArrayHash TableDivide and ConquerTreeBinary Tree

Construct Binary Tree from Inorder and Postorder Traversal

LeetCode
1 approach, code in all languages

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.
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