Loading content...
You are given two integer arrays representing two different traversal sequences of the same binary tree containing distinct node values:
Your task is to reconstruct the original binary tree using only these two traversal sequences and return its root node.
In a preorder traversal, we visit:
In a postorder traversal, we visit:
Unlike reconstruction from preorder + inorder (or postorder + inorder), reconstructing from preorder + postorder can yield multiple valid trees when nodes have only one child. This is because a single child could be either a left child or a right child — both interpretations produce the same preorder and postorder sequences.
In such ambiguous cases, you may return any valid binary tree that produces the given traversal sequences.
Return the root of the reconstructed binary tree. The tree will be verified by performing a level-order traversal and comparing the node values.
preorder = [1,2,4,5,3,6,7]
postorder = [4,5,2,6,7,3,1][1,2,3,4,5,6,7]The reconstructed tree has root 1, with left child 2 and right child 3. Node 2 has children 4 and 5. Node 3 has children 6 and 7. The level-order traversal of this tree produces [1,2,3,4,5,6,7].
preorder = [1]
postorder = [1][1]A single-node tree with value 1. This is the only possible reconstruction.
preorder = [1,2,3]
postorder = [2,3,1][1,2,3]Node 1 is the root. Since both children 2 and 3 exist, the tree structure is uniquely determined. Node 2 is the left child and node 3 is the right child of the root.
Constraints