#572

Subtree of Another Tree

Easy
TreeDepth-First SearchString MatchingBinary TreeHash FunctionDepth-First SearchRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal approach uses a single traversal of the main tree while checking for subtree matches. This reduces the number of checks significantly compared to the brute force method.

⚙️

Algorithm

4 steps
  1. 1Step 1: Traverse the main tree using a depth-first search (DFS).
  2. 2Step 2: For each node, check if it matches the root of subRoot.
  3. 3Step 3: If it matches, check if the entire subtree matches using a helper function.
  4. 4Step 4: If a match is found, return true; otherwise, continue searching.
solution.py21 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class Solution:
9    def isSubtree(self, root: TreeNode, subRoot: TreeNode) -> bool:
10        if not root:
11            return False
12        if self.isSameTree(root, subRoot):
13            return True
14        return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
15
16    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
17        if not p and not q:
18            return True
19        if not p or not q:
20            return False
21        return (p.val == q.val) and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Complexity note: The time complexity is O(n) because we traverse each node in the main tree once. The space complexity is O(h) due to the recursive call stack, where h is the height of the tree.

  • 1Understanding tree traversal is crucial for solving tree-related problems.
  • 2Recognizing when to use helper functions for subtree comparisons can simplify code.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.