Skip to content

Commit

Permalink
(4.10) Check Subtree py
Browse files Browse the repository at this point in the history
  • Loading branch information
ktorng committed Oct 30, 2017
1 parent 37e27ee commit d3f6236
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions CrackingTheCodingInterview/ch04-TreesAndGraphs/checkSubtree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""
T1 and T2 are two very large binary trees, with T1 much bigger
than T2 - create an algorithm to determine if T2 is a subtree
of T1
"""


# Traverse t1 until find value equal to t2, then check match_trees
def is_subtree(t1, t2):
if not t2:
return True

if not t1:
return False

if match_trees(t1, t2):
return True

return is_subtree(t1.left, t2) or \
is_subtree(t1.right, t2)


# Check if trees match exactly
def match_trees(t1, t2):
# Both subtrees empty
if not t1 and not t2:
return True

# One subtree empty
if not t1 or not t2:
return False

# Values don't match
if t1.value !== t2.value:
return False

# Check both sides
return match_trees(t1.left, t2.left) and \
match_trees(t1.right, t2.right)

0 comments on commit d3f6236

Please sign in to comment.