/106. Construct Binary Tree from Inorder and Postorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

Medium
Arrays68.2% acceptance

Given two integer arrays representing the inorder and postorder traversals of a binary tree, reconstruct the binary tree and return its level-order traversal as a list. Each node value is unique. If a node does not exist at a position in the level-order traversal, use None.

Example 1

Input: inorder = [2,1,4,3,5], postorder = [2,4,5,3,1]

Output: [1,2,3,None,None,4,5]

Explanation: The reconstructed tree is: 1 / \ 2 3 / \ 4 5 Level-order: [1,2,3,None,None,4,5]

Example 2

Input: inorder = [10], postorder = [10]

Output: [10]

Explanation: Single node tree.

Constraints

  • 1 <= len(inorder) <= 3000
  • len(postorder) == len(inorder)
  • -3000 <= inorder[i], postorder[i] <= 3000
  • All values in inorder and postorder are unique
  • Each value in postorder appears in inorder
  • inorder is the inorder traversal of the tree
  • postorder is the postorder traversal of the tree
Python (current runtime)

Case 1

Input: inorder = [6,2,8,5,9], postorder = [6,8,9,5,2]

Expected: [2,6,5,None,None,8,9]

Case 2

Input: inorder = [7,3,1], postorder = [7,1,3]

Expected: [3,7,1]

Case 3

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

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