Skip to problem
←

Construct Binary Tree from Preorder and Postorder Traversal

Medium 0 attempts

You're given two arrays, preorder and postorder, holding the preorder and postorder traversals of the same binary tree whose node values are all distinct. Return any binary tree with these traversals. The original shape is not necessarily unique.

Preorder visits root, left subtree, then right subtree. Postorder visits left subtree, right subtree, then root. When a node has only one child, these traversals cannot tell whether it is a left or right child.

Function contract

Implement constructFromPrePost(preorder, postorder). These arrays are valid traversals of the same tree with distinct values.

Output: A root node with val, left, and right fields. Any tree matching both traversals is accepted; the runner displays it as a level-order array with trailing nulls removed.

Example 1

Input
preorder = [1,2,4,5,3,6,7]
postorder = [4,5,2,6,7,3,1]
Output
[1,2,3,4,5,6,7]

Example 2

Input
preorder = [1]
postorder = [1]
Output
[1]
Visual Aid
Both shapes are valid
1212Preorder [1,2] · Postorder [2,1]

Either tree may be returned for these traversals. The checker compares traversals rather than requiring one fixed shape.

Constraints
  • 1 <= preorder.length <= 30
  • preorder and postorder are permutations of 1..n
  • Both arrays have equal length and describe at least one valid binary tree.

Recursive Construction

The first element of preorder is root, the second begins the first child subtree. We choose to attach that subtree on the left; if it is the only child, either side is valid. Find it in postorder to determine left subtree size.

javascript
function constructFromPrePost(preorder, postorder) {
  let preIdx = 0;
  const postMap = new Map();
  postorder.forEach((v, i) => postMap.set(v, i));
  function build(postLo, postHi) {
    if (postLo > postHi || preIdx >= preorder.length) return null;
    const node = { val: preorder[preIdx++], left: null, right: null };
    if (postLo === postHi) return node;
    const leftRootIdx = postMap.get(preorder[preIdx]);
    node.left = build(postLo, leftRootIdx);
    node.right = build(leftRootIdx + 1, postHi - 1);
    return node;
  }
  return build(0, postorder.length - 1);
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript