Construct Binary Tree from Inorder and Postorder Traversal

Medium#106build a tree

You get two traversals of the same binary tree with distinct values: inorder (left subtree, node, right subtree) and postorder (left subtree, right subtree, node). Rebuild the tree. Our traversals: inorder [9, 8, 4, 7, 2, 5], postorder [8, 9, 7, 5, 2, 4] — the tree, level by level, is [4, 9, 2, none, 8, 7, 5].

input
inorder and postorder: the inorder (left, root, right) and postorder (left, right, root) traversals of one binary tree whose values are all different.
returns
The root of that tree: there is only one, since the values are all different.
constraints
  • 1 ≤ inorder.length ≤ 3000
  • postorder.length = inorder.length
  • −3000 ≤ inorder[i], postorder[i] ≤ 3000
  • the values of inorder are all different
  • inorder and postorder are traversals of the same tree
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
function buildTree(inorder, postorder) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more divide and conquer problems

Pattern “Divide and conquer” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.