Skip to content

Instantly share code, notes, and snippets.

@andreit
Created January 12, 2021 04:48
Show Gist options
  • Save andreit/0b17306a05c130f65ea15c0fde73d474 to your computer and use it in GitHub Desktop.
Save andreit/0b17306a05c130f65ea15c0fde73d474 to your computer and use it in GitHub Desktop.
t1 = {
"value": 1,
"children": [
{
"value": 2,
"children": [
{"value": 3},
{"value": 4}
]
},
{
"value": 5,
"children": [
{"value": 6},
{"value": 7}
]
}
]
}
t2 = {
"value": 5,
"children": [
{"value": 6},
{"value": 7}
]
}
def match(t1, t2):
"""Returns True if t1 matches t2, False otherwise."""
if t1["value"] != t2["value"]:
return False
t1_children = t1.get("children", [])
t2_children = t2.get("children", [])
if not t1_children and not t2_children:
return True
lmatch = match(t1_children[0], t2_children[0])
rmatch = match(t1_children[1], t2_children[1])
return lmatch and rmatch
def issubtree(t1, t2):
"""Returns True if t2 is a subtree of t1, False otherwise."""
if t1["value"] != t2["value"]: # no match, continue searching t1's nodes
t1_children = t1.get("children", [])
if t1_children:
lmatch = issubtree(t1_children[0], t2)
rmatch = issubtree(t1_children[1], t2)
return lmatch or rmatch
return False
else: # match, compare the rest of the nodes
return match(t1, t2)
print(issubtree(t1, t2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment