In the "Subtree of Another Tree" problem, you are given two binary trees: root and subRoot. You need to determine if subRoot is a subtree of root. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. Crucially, the subtree must match exactly—not just in structure, but in all node values, and it must go all the way to the leaf nodes.
This is a classic recursion problem frequently asked by Google, Bloomberg, and Amazon. it evaluates a candidate's understanding of tree traversal (specifically Depth-First Search) and their ability to solve a nested recursive problem. To solve it, you have to recursively check every node in the main tree to see if the tree starting at that node is identical to the given subRoot.
The pattern used is "Nested Recursion" or "Double DFS." One recursive function (let's call it isSubtree) traverses the main tree. For every node it visits, it calls a second recursive helper function (let's call it isSameTree). isSameTree checks if two trees are identical by comparing their root values and then recursively checking their left and right subtrees.
Imagine Tree A has a root 3, with children 4 and 5. Node 4 has children 1 and 2. Tree B has a root 4, with children 1 and 2. To check if B is a subtree of A:
null at the same time. If one tree has a child and the other doesn't, they are not the same.Mastering the "Is Same Tree" problem is the prerequisite for this one. Once you can confidently write a recursive function to check if two trees are identical, "Subtree of Another Tree" becomes a simple matter of applying that check at every node of a larger tree. Practice visualizing recursive calls as a stack to avoid confusion.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Leaf-Similar Trees | Easy | Solve | |
| Balanced Binary Tree | Easy | Solve | |
| Sum of Root To Leaf Binary Numbers | Easy | Solve | |
| Evaluate Boolean Binary Tree | Easy | Solve | |
| Diameter of Binary Tree | Easy | Solve |