15% off all plans & roadmaps Use code
See plansLeetCode 572 · Solution & editorial
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.
Subtree of Another Tree is a Tree Traversal Patterns (DFS & BFS) problem, in the Serialization and Deserialization subpattern. The pattern covers preorder, inorder, level order traversal, LCA, and serialization
Learn to serialize and deserialize binary trees. Convert trees to strings and reconstruct them.
The reference solution runs in O(m * n) time and O(h) space.
Subtree of Another Tree has been reported in interviews at Amazon, Microsoft, Facebook.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Subtree of Another Tree is a Tree Traversal Patterns (DFS & BFS) problem, in the Serialization and Deserialization subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.