Subtree of Another Tree
Master this topic with zero to advance depth.
Subtree of Another Tree
Check if a tree subRoot is a subtree of root.
Examples
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true
Approach 1
Level I: Recursive DFS (Is Match?)
Intuition
A tree s is a subtree of t if:
sandtare identical.sis a subtree oft.left.sis a subtree oft.right.
⏱ O(M * N) (where M, N are nodes in each tree)💾 O(H)
Detailed Dry Run
root(3) != sub(4). check root(4) == sub(4) -> YES (IsSameTree).
Approach 2
Level II: Preorder String Matching (O(N))
Intuition
Serialize both trees into strings using preorder traversal. Add special markers for null nodes (e.g., '#') and separate values to avoid ambiguity (e.g., ','). If the serialized subRoot is a substring of serialized root, it's a subtree.
Diagram
Tree: 3(4,5) -> Preorder: ",3,4,#,#,5,#,#"
Subtree: 4 -> Preorder: ",4,#,#"
Match found in ",3,4,#,#,5,#,#"!⏱ O(N + M)💾 O(N + M)
Detailed Dry Run
Serialize root: ^3,4,1,#,#,2,#,#,5,#,#. Serialize sub: ^4,1,#,#,2,#,#. Sub exists in Root -> True.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.