↓Skip to main content
  1. LeetCode/

LeetCode 572: Subtree of Another Tree

·2 mins· ·
LeetCode Easy Tree Depth-First-Search String-Matching Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-27

  • Submissions: Wrong Answer ×2 → Accepted ×2 → Runtime Error → Wrong Answer ×2 → Accepted ×2 → Runtime Error ×3 → Wrong Answer ×3 → Accepted ×2 → Wrong Answer → Accepted → Wrong Answer ×3 → Accepted

Approach
#

A subtree must match from some node all the way down (Tree Template 1). So compare at every node of root with LC 100’s check:

  • If the tree rooted here equals subRoot, return True.
  • Otherwise keep searching the left and right subtrees (call isSubtree, not isSame).

My Attempts
#

This took 23 submissions:

  • Attempt 1’s stack only popped, never pushed children, and never really compared trees, so even [1] and [1] returned False.
  • Many later versions had the same bug: after checking the root, they called only isSame(root.left, subRoot) and isSame(root.right, subRoot), reaching just the second level. With root [1, 1, 1, 2] and subRoot [2], the 2 is on the third level, so the answer is True; they returned False.

Solution
#

class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        def same(a, b):
            if not a or not b:
                return a is b
            return a.val == b.val and same(a.left, b.left) and same(a.right, b.right)
        if not root:
            return False
        return same(root, subRoot) or self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)

Complexity
#

Time O(m · n), space O(h). Serializing and string matching gives O(m + n).

Mistakes to Avoid
#

  • Recurse with isSubtree when searching down, or only the second level gets checked.
  • An empty root returns False (subRoot has at least one node).

Interview Explanation
#

At every node of the main tree I check whether its subtree is identical to the target, returning True on a match and otherwise searching both subtrees. Time O(mn).

Related

LeetCode 563: Binary Tree Tilt
·1 min
LeetCode Easy Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 563 note: return subtree sums in post-order; each node’s tilt is the difference of its subtree sums, added to the answer
LeetCode 501: Find Mode in Binary Search Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 501 note: a BST’s in-order is sorted, so equal values are contiguous; count the current run during in-order, resetting the answer on a new maximum and appending on a tie
LeetCode 543: Diameter of Binary Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Tree Dp-on-Trees
LeetCode 543 note: the diameter may skip the root; return heights in post-order while updating the answer with left + right height at every node, counting edges
LeetCode 404: Sum of Left Leaves
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 404 note: tell each child during DFS whether it is a left child, adding only left children that are leaves
LeetCode 226: Invert Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 note: swap every node’s children, using a simultaneous assignment so the already-changed side is not reused
LeetCode 145: Binary Tree Postorder Traversal
·2 mins
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 145 note: iterative post-order pushes a node back with a visited flag on its first pop, then the right and left children; record it on the second pop