# 572 Subtree of Another Tree

Given two non-empty binary treessandt, check whether treethas exactly the same structure and node values with a subtree ofs. A subtree ofsis a tree consists of a node insand all of this node's descendants. The treescould 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)

``````# 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("#")``````

Last updated