Subtree of Another Tree

Subtree of Another Tree – Easy Level Problem

Given the roots of two binary trees, root and subRoot, return true if subRoot is a subtree of root, otherwise return false.

A subtree of a binary tree is a tree consisting of a node in the binary tree and all its descendants. The binary tree itself is also considered its own subtree.

Subtree of Another Tree problem

Example 1:

Subtree of Another Tree problem 1

Example 2:

Subtree of Another Tree problem 2

Constraints:

  • 0 <= The number of nodes in both trees <= 100.
  • -100 <= root.val, subRoot.val <= 100

Hints to Solve Subtree of Another Tree

Recommendation for Time and Space Complexity:

Aim for a solution with a time complexity of O(m x n) or better and a space complexity of O(m + n).

Where, m and n, number of nodes in roots and subroots.

Hint 1 :

  • Subtree of a tree is a smaller tree rooted at a specific node of the larger tree.
  • To check if subRoot matches any subtree of root, think about using recursion.
  • You can use the approach where you check if two trees are identical in structure and values.

Hint 2 :

  • Two trees are identical when they have the same structure and all corresponding nodes have the same values.
  • Use Depth First Search (DFS) to solve this problem by comparing the trees node by node. How would you implement this in code?

Hint 3 :

  • Traverse the root tree, and for each node, check if the subtree starting at that node matches subRoot.
  • Use a helper function, sameTree(root1, root2), to verify if the two trees are identical in structure and node values.

There are mainly 2 approach to solve this problem:

  1. Depth First Search (DFS)
  2. Serialization And Pattern Matching

1. Depth First Search (DFS) Method

Traverse the main tree (root) using DFS, and at each node, check if the subtree starting from that node matches subRoot. Use a helper function to compare the structure and values of the two trees recursively.

  • Time complexity: O(m x n)
  • Space complexity: O(m + n)

Where m is the number of nodes in subRoot and n is the number of nodes in root.

Code

2. Serialization And Pattern Matching Method

Serialize both trees into strings, where each tree is represented as a unique sequence of node values and structure. Use pattern matching to check if the serialized subRoot appears as a substring in the serialized root.

  • Time complexity: O(m + n)
  • Space complexity: O(m + n)

Code

3. Breadth First Search Method

The BFS method uses a queue to traverse the tree level by level. Nodes at the same depth are processed together. By counting the levels traversed, you determine the maximum depth of the tree. This approach is efficient for level-order traversal.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

More Articles