# 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: 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:

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

The question should be specific, self-contained, and written in natural language.
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.
