Leetcode 572: Subtree of Another Tree

grid47
grid47
Exploring patterns and algorithms
Sep 10, 2024 6 min read

A tree being checked for its subtree, with the subtree softly glowing as it is found.
Solution to LeetCode 572: Subtree of Another Tree Problem

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 consists of a node in the tree and all of this node’s descendants.
Problem
Approach
Steps
Complexity
Input: The input consists of two binary trees, represented by their root nodes.
Example: Input: root = [1, 2, 3, 4, 5], subRoot = [2, 4, 5]
Constraints:
• 1 <= Number of nodes in root <= 2000
• 1 <= Number of nodes in subRoot <= 1000
• -10^4 <= node values <= 10^4
Output: The output should be a boolean value: true if a subtree of root matches subRoot, false otherwise.
Example: Output: true
Constraints:
• The result should be a boolean value.
Goal: The goal is to check if any subtree in root matches subRoot in both structure and values.
Steps:
• Start by checking if the root node matches the subRoot tree using a helper function to compare the trees.
• If the root node doesn't match, recursively check the left and right subtrees of root.
• If a match is found, return true; otherwise, return false.
Goal: The problem constraints ensure that both trees root and subRoot are non-empty and contain at least one node.
Steps:
• 1 <= Number of nodes in root <= 2000
• 1 <= Number of nodes in subRoot <= 1000
• -10^4 <= node values <= 10^4
Assumptions:
• Both root and subRoot are valid binary trees with integer values.
• The function should handle large trees up to the input size limits efficiently.
Input: Input: root = [1, 2, 3, 4, 5], subRoot = [2, 4, 5]
Explanation: The subtree rooted at node 2 in root matches the structure and values of subRoot, so the output is true.

Input: Input: root = [1, 2, 3, 4, 5], subRoot = [2, 3, 5]
Explanation: There is no subtree of root that matches subRoot exactly, so the output is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus