Logo for ammarahmed.ca
Easy
Jan 12, 2026
#binary-tree
#dfs

572. Subtree of Another Tree

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.

A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.

Example 1:

1Input: root = [3,4,5,1,2], subRoot = [4,1,2] 2Output: true

Example 2:

1Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] 2Output: false
  • The number of nodes in the root tree is in the range [1, 2000].
    • The number of nodes in the subRoot tree is in the range [1, 1000].
      • -104 <= root.val <= 104
        • -104 <= subRoot.val <= 104

          Constraints:

          Notes

          Intuition

          A subtree must match exactly starting from some node in the main tree. We need to check at every node whether the subtree rooted there is identical to subRoot.

          Implementation

          Create a helper function isSame that checks if two trees are identical (same structure and values). In the main function, if subRoot is null, it's trivially a subtree. If root is null but subRoot isn't, return false. Check if the current root matches subRoot using isSame. If not, recursively check if subRoot is a subtree of either the left or right child.

          Edge-cases

          A null subRoot is considered a subtree of any tree. Handle the case where root becomes null during recursion (subRoot can't exist in an empty tree).

          • Time: O(m * n) — where m and n are the sizes of the two trees
            • Space: O(n) — recursion stack

              Complexity

              Solution

              1from typing import Optional 2from lcutils import TreeNode 3 4# Definition for a binary tree node. 5# class TreeNode: 6# def __init__(self, val=0, left=None, right=None): 7# self.val = val 8# self.left = left 9# self.right = right 10class Solution: 11 def isSame(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: 12 if not p and not q: 13 return True 14 if p and q and p.val == q.val: 15 return self.isSame(p.left, q.left) and self.isSame(p.right, q.right) 16 else: 17 return False 18 def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: 19 if not subRoot: 20 return True 21 if not root: 22 return False 23 if self.isSame(root, subRoot): 24 return True 25 return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) 26 27 28 29 30if __name__ == "__main__": 31 # Include one-off tests here or debugging logic that can be run by running this file 32 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 33 solution = Solution() 34