Last active
December 27, 2015 10:39
-
-
Save DeaconDesperado/7313344 to your computer and use it in GitHub Desktop.
Recursive subtree check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def contains_tree(a,b): | |
if b is None: | |
#an empty child tree is always a subtree | |
return True | |
return sub_tree(a,b) | |
def sub_tree(a,b): | |
if a is None: | |
#if larger tree is exhausted, return false | |
return False | |
if a == b: | |
#if matching point is found, check descending data | |
if match_tree(a,b): return True | |
#recurse until any matches are found | |
return sub_tree(a.left,b) or sub_tree(a.right,b) | |
def match_tree(a,b): | |
if b is None and a is None: | |
#if match is exhaustive on both trees, the subtree | |
#and parent terminate with the same vals | |
return True | |
if a is None or b is None: | |
#if only one tree exhausts, cannot be subtree | |
return False | |
if a != b: | |
#if the data does not match, trees are different | |
return False | |
#recursively match data on all descendents (both sides) | |
return match_tree(a.left,b.left) and match_tree(a.right,b.right) | |
print contains_tree(tree_a.root,tree_b.root) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment