Blind 75
33 / 75Free practice

Construct Binary Tree From Preorder and Inorder Traversal

Medium · Trees

Jump to code

Rebuild a binary tree from valid preorder and inorder arrays containing the same distinct values. Return the root.

Examples

Example 1

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Output: [3,9,20,null,null,15,7]

Example 2

preorder = [-1]
inorder = [-1]

Output: [-1]

Constraints

  • 1 <= inorder.length <= 1000
  • inorder.length == preorder.length
  • -1000 <= preorder[i], inorder[i] <= 1000

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

Need a hint?

Preorder identifies the root; its inorder position splits the subtrees.

Asked in real interviews

Candidates reported versions of Construct Binary Tree From Preorder and Inorder Traversal from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    3,
    9,
    20,
    15,
    7
  ],
  [
    9,
    3,
    15,
    20,
    7
  ]
]
Expected
[
  3,
  9,
  20,
  null,
  null,
  15,
  7
]
Case 2
Input
[
  [
    -1
  ],
  [
    -1
  ]
]
Expected
[
  -1
]
Case 3
Input
[
  [
    1,
    2,
    3
  ],
  [
    2,
    1,
    3
  ]
]
Expected
[
  1,
  2,
  3
]
Case 4
Input
[
  [
    1,
    2
  ],
  [
    2,
    1
  ]
]
Expected
[
  1,
  2
]
Case 5
Input
[
  [
    1,
    2,
    4,
    5,
    3
  ],
  [
    4,
    2,
    5,
    1,
    3
  ]
]
Expected
[
  1,
  2,
  3,
  4,
  5
]

Drafts are saved per language in this browser when storage is available.