Unique Binary Tree Requirements

easy

Two traversal techniques are given by their codes: 1 = preorder, 2 = inorder, 3 = postorder. Given two codes a and b, return true if a unique binary tree can be constructed from those two traversals, and false otherwise.

Hints

Codes: 1 = preorder, 2 = inorder, 3 = postorder.
Preorder/postorder give the root; only inorder gives the left/right split.
A unique tree is possible iff one of the two traversals is inorder.

Common doubts

They both identify the root but neither tells you where the left subtree ends, so a node with a single child is ambiguous.
Given the root, inorder splits the remaining nodes into the left subtree (before the root) and right subtree (after).

Interview follow-ups

Take preorder[0] as the root, find it in inorder to split, and recurse on the two halves — O(n) with a value->index hash map.

Fun facts

  • A full binary tree (every node has 0 or 2 children) CAN be reconstructed from preorder + postorder, because the single-child ambiguity never arises.

Asked at

AmazonAdobe
Frequently Sometimes Occasionally
Example 1
Input: a = 1, b = 2
Output: true
Preorder + inorder determine a unique tree.
Example 2
Input: a = 1, b = 3
Output: false
Preorder + postorder do not determine a unique tree.
Constraints

- 1 <= a, b <= 3 - a and b are traversal codes (1=preorder, 2=inorder, 3=postorder)

Solve this problem →