Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created September 20, 2018 21:09
Show Gist options
  • Select an option

  • Save yokolet/c08be054c9f980d53c3d896af446d635 to your computer and use it in GitHub Desktop.

Select an option

Save yokolet/c08be054c9f980d53c3d896af446d635 to your computer and use it in GitHub Desktop.
Subtree of Another Tree
"""
Description:
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.
Examples:
Input:
tree s 3
/ \
4 5
/ \
1 2
tree t 4
/ \
1 2
Output: True
Input:
tree s 3
/ \
4 5
/ \
1 2
/
0
tree t 4
/ \
1 2
Output: False
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isSubtree(s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def serialize(node):
if node:
return '^' + str(node.val) + serialize(node.left) + serialize(node.right)
else:
return '$'
print(serialize(t), serialize(s))
return serialize(t) in serialize(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment