Skip to content
BASA DSA

Construct Binary Tree From Preorder And Inorder Traversal

MediumTrees

Reconstruct and return a binary tree from its preorder and inorder value sequences.

Example 1

Input
preorder = [4,2,1,3,6]
inorder = [1,2,3,4,6]
Output
[4,2,6,1,3]

Explanation

Preorder selects root 4; inorder splits [1,2,3] left and [6] right, then gives 2 children 1 and 3.

Example 2

Input
preorder = [7]
inorder = [7]
Output
[7]

Explanation

Singleton traversals reconstruct leaf 7.

Example 3

Input
preorder = [1,2,3]
inorder = [3,2,1]
Output
[1,2,null,3]

Explanation

Each next preorder value falls in the left inorder segment, producing chain 1->2->3.

Constraints

  • 1 <= number of nodes <= 3000
  • Values are distinct
  • Both arrays describe the same valid tree

Function contractbuildTreeArguments: json, json
Loading draft…
SolutionRuns on your device
Loading draft…