KatInterview

Reconstruct Binary Tree from Inorder and Postorder Sequences

Trees & GraphsModel answer
MediumModel answerTrees & Graphstrees-graphsrecursionhash-table

Last updated

Reconstruct a binary tree given its inorder and postorder traversal arrays, assuming all node values are unique.

Given two integer arrays, inorder and postorder, representing the inorder and postorder traversals of the same binary tree respectively, reconstruct and return the original binary tree.

Assumptions & Constraints

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • All values in inorder and postorder are unique.
  • It is guaranteed that inorder and postorder form a valid binary tree.

Example 1

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

Example 2

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

Hints

Hint 1

Recall what the last element of a postorder traversal represents.

Hint 2

How does finding the root value in the inorder sequence divide the tree into left and right subtrees?

Hint 3

If you consume the postorder array backwards, which subtree's root do you encounter first: left or right?