> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/interview-practice-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/572-subtree-of-another-tree.md).

# 572 Subtree of Another Tree

Given two non-empty binary trees**s**and**t**, check whether tree**t**has exactly the same structure and node values with a subtree of**s**. A subtree of**s**is a tree consists of a node in**s**and all of this node's descendants. The tree**s**could also be considered as a subtree of itself.

**Example 1:**\
Given tree s:

```
     3
    / \
   4   5
  / \
 1   2
```

Given tree t:

```
   4 
  / \
 1   2
```

Return **true**

, because t has the same structure and node values with a subtree of s.

**Example 2:**\
Given tree s:

```
     3
    / \
   4   5
  / \
 1   2
    /
   0
```

Given tree t:

```
   4
  / \
 1   2
```

Return **false**

**The Idea:** The idea is to perform some kind of traversal that is non unique to both trees. The problem then just simplifies into checking if tree **t** has a sub-traversal as tree **s**. In order words, return true if tree **t** contains a subarray in tree **s**. The only tricky part to this is understanding that we want to capture complete subtrees. In other words, both sequences must have the same sequence of null terminators. This is why we append unique characters '$' and '#' for the left and right null terms.

**Complexity:** O(n^2) time O(n) space (can be reduced to O(n) time with either ukkonens or KMP string matching algorithm)

```python
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def contains_subarray(self, ar1, ar2):
        iter = 0
        go_to = len(ar2) - len(ar1)
        while (iter <= go_to):
            cur_sub = ar2[iter:len(ar1) + iter]
            if (cur_sub == ar1):
                return True
            iter += 1
        return False

    def isSubtree(self, s, t):
        """
        :type s: TreeNode
        :type t: TreeNode
        :rtype: bool
        """
        arr_s = []
        arr_t = []
        self.generate_preOrder_string(s, arr_s, False)
        self.generate_preOrder_string(t, arr_t, False)
        return self.contains_subarray(arr_t, arr_s)

    def generate_preOrder_string(self, node, cum_str, isLeft):
        if node:
            cum_str.append(str(node.val)) 
            self.generate_preOrder_string(node.left, cum_str, False)
            self.generate_preOrder_string(node.right, cum_str, True)
        elif(isLeft):
            cum_str.append("$") 
        else:
            cum_str.append("#")
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/572-subtree-of-another-tree.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
