1637. Rebuild a Full Tree

A full binary tree is one where every node has either zero or two children. All values in the tree are distinct. You are given two arrays describing the same full tree: preorder (node, left subtree, right subtree) and postorder (left subtree, right subtree, node).

Rebuild the tree and return its root. For a full binary tree with distinct values the two traversals identify exactly one tree, so the answer is unique. The arrays always come from a valid full tree, and the number of nodes is odd.

Observe that a node's left child is the next value in preorder, and the position of that value in postorder tells you how many nodes the left subtree has. Aim for O(n) time using a value-to-index map, and O(n) space.

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]
Explanation:

The tree is 1 with children 2 (leaves 4, 5) and 3 (leaves 6, 7); its level-order is 1, 2, 3, 4, 5, 6, 7.

Example 2

Input:
preorder = [8], postorder = [8]
Output:
[8]
Explanation:

A single value forms a one-node tree.

Example 3

Input:
preorder = [10,20,30], postorder = [20,30,10]
Output:
[10,20,30]
Explanation:

Root 10 has leaf children 20 and 30.

Constraints

1 ≤ n ≤ 499, n odd

values distinct in [1, 104]

the arrays are valid traversals of a full binary tree

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…