/105. Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal

Medium
Arrays68.5% acceptance

Given two integer arrays preorder_sequence and inorder_sequence representing the preorder and inorder traversals of a binary tree with unique values, reconstruct the binary tree and return its level-order traversal as a list, where null represents missing children.

Example 1

Input: preorder_sequence = [10,5,2,8,15,12,20], inorder_sequence = [2,5,8,10,12,15,20]

Output: [10,5,15,2,8,12,20]

Explanation: The reconstructed tree is: 10 / \ 5 15 / \ / \ 2 8 12 20 Level-order: [10,5,15,2,8,12,20]

Example 2

Input: preorder_sequence = [1,2,3], inorder_sequence = [2,1,3]

Output: [1,2,3]

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

Example 3

Input: preorder_sequence = [4], inorder_sequence = [4]

Output: [4]

Explanation: Single node tree.

Constraints

  • 1 <= len(preorder_sequence) <= 3000
  • len(inorder_sequence) == len(preorder_sequence)
  • -3000 <= preorder_sequence[i], inorder_sequence[i] <= 3000
  • All values in preorder_sequence and inorder_sequence are unique
  • Each value in inorder_sequence also appears in preorder_sequence
  • preorder_sequence and inorder_sequence are valid traversals of the same binary tree
Python (current runtime)

Case 1

Input: preorder_sequence = [7,3,1,5,9,8,10], inorder_sequence = [1,3,5,7,8,9,10]

Expected: [7,3,9,1,5,8,10]

Case 2

Input: preorder_sequence = [6,2,1,4,8,7,9], inorder_sequence = [1,2,4,6,7,8,9]

Expected: [6,2,8,1,4,7,9]

Case 3

Input: preorder_sequence = [100], inorder_sequence = [100]

Expected: [100]