Construct Binary Tree from Inorder and Postorder Traversal

Given two integer arrays `inorder` and `postorder`, the inorder and postorder traversals of the same binary tree with unique values, rebuild the tree and return its root.

30:00

Construct Binary Tree from Inorder and Postorder Traversal
medium
Free written solution
Topics
Companies

Given two integer arrays inorder and postorder, the inorder and postorder traversals of the same binary tree with unique values, rebuild the tree 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]
Constraints:
  • 1≤inorder.length≤30001 \leq \text{inorder.length} \leq 3000

  • postorder.length==inorder.length\text{postorder.length} == \text{inorder.length}

  • −3000≤inorder[i],postorder[i]≤3000-3000 \leq \text{inorder}[i], \text{postorder}[i] \leq 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 and postorder its postorder traversal.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"inorder":[9,3,15,20,7],"postorder":[9,15,7,20,3]}

Map every inorder value to its index so the root of any window can be split in O(1). There are 5 values.

postorder (read right to left)inorder (node columns)9157203post903115220374

calls (depth 0):

none

nodes built: 0 / 5

current root
inorder window
left part
right part
built node
Variables
VariableValue
post4
lonull
hinull
midnull
DepthFunction Call
Stack empty
0/38