oneby7

Binary Trees Building and serializing

381. Construct Binary Tree from Inorder and Postorder Traversal

Medium

You are given two integer arrays, inorder and postorder. They are the inorder and the postorder traversal of the same binary tree. Build that tree and return its root.

An inorder traversal lists the left subtree in inorder, then the node, then the right subtree in inorder. A postorder traversal lists the left subtree in postorder, then the right subtree in postorder, then the node. All the values in the tree are distinct.

The output shows the tree you return level by level, from left to right, with null where a child is missing. So [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

4-17102-6

Input: inorder = [4, -1, 7, 10, 2, -6] postorder = [-1, 7, 4, 2, -6, 10]

Output: [10,4,-6,null,7,2,null,-1]

Explanation: The tree has the root 10. Its left child 4 has a right child 7, and 7 has a left child -1. Its right child -6 has a left child 2. Listing left, node, right from the root gives 4, -1, 7, 10, 2, -6, and listing left, right, node gives -1, 7, 4, 2, -6, 10.

Example 2

10⁹

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

Output: [1000000000]

Explanation: One value, so the tree is a single node.

Example 3

235

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

Output: [2,null,5,3]

Explanation: The root 2 has a right child 5, and 5 has a left child 3. The root has no left child, so the output shows null in its place.

Check your understanding

Work out the answer for this input before you write any code.

inorder = [1, 3, 6, 8], postorder = [1, 3, 8, 6]

Constraints

  • 1 ≤ inorder.length ≤ 105
  • postorder.length == inorder.length
  • -109 ≤ inorder[i], postorder[i] ≤ 109
  • All the values are distinct.
  • inorder and postorder are the inorder and postorder traversals of one binary tree.
  • That tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.