Tree Construction & Serialization
O(n)
Preorder/postorder gives the root; inorder splits left vs right subtree. Recurse on the partitions.
Learn firstTree DFS (Paths & Recursion)
0%
mastery
0/11 solved
0/11 solved
Recognise it
The signal
Rebuild a tree from two traversals (preorder+inorder), serialize/deserialize to a string, or flatten/convert its structure.
1Brute force
Search inorder for each root: O(n2).
2The observation
Linear search for the root in inorder: a value->index map makes each split O(1).
3Why it works
The next preorder element is the root of the subtree being built; its inorder index splits span [l, r] into left and right.
Reach for it when
- +serialize/deserialize
- +flatten/convert structure
Not when
- ×Values have duplicates: the inorder split is ambiguoususe Build from unique ids, or serialize with null markers
- ×Only preorder + postorder are given: not unique unless the tree is fulluse Need inorder, or a full-tree guarantee
Practice
0/11 solved
- Convert Sorted Array to Binary Search TreeFoundationFoundationAmazon, AdobeEasy
- Construct Binary Tree from Preorder and Inorder TraversalApply it · Two traversals define the tree.Apply itAmazon, MicrosoftMedium
- Construct Binary Tree from Inorder and Postorder TraversalOne change · Roots come from the end.One changeMedium
- Construct Binary Search Tree from Preorder TraversalTwists · Only one traversal, but BST order is implicit.TwistsMedium
- Flatten Binary Tree to Linked ListBranches · Restructure in place.BranchesMeta, AmazonMedium
- Serialize and Deserialize Binary TreeAdvanced · Design an encoding.AdvancedAmazon, MetaHard
- Serialize and Deserialize BSTMastery checkMastery checkMedium
- Subtree of Another TreeMeta, AmazonEasy
- Tree TraversalsCSESMedium
- Tree Isomorphism ICSESMedium
- Tree Isomorphism IICSESMedium
Pitfalls
Classic bugs
- !Serialized without null markers: the string is ambiguous and can't be decoded. Emit a marker for every null child.
Go deepervariants and techniques · 1 combinations · resources
Combinations
Tree Hashing / Canonical Forms+Topological Sort
are two unrooted trees isomorphic
- Tree Hashing / Canonical Forms:
- a canonical id of the tree rooted at each centre
- Topological Sort:
- leaf trimming finds the 1-2 centres of an unrooted tree