Subtree
Source
You have two every large binary trees: T1, with
millions of nodes, and T2, with hundreds of nodes.
Create an algorithm to decide if T2 is a subtree of T1.
Example
T2 is a subtree of T1 in the following case:
1 3
/ \ /
T1 = 2 3 T2 = 4
/
4
T2 isn't a subtree of T1 in the following case:
1 3
/ \ \
T1 = 2 3 T2 = 4
/
4
Note
A tree T2 is a subtree of T1 if there exists a node n
in T1 such that the subtree of n is identical to T2.
That is, if you cut off the tree at node n, the two trees would be identical.
Python
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
def isSubtree(self, T1, T2):
if T2 is None:
return True
if T1 is None:
return False
if T1.val==T2.val and self.isSameTree(T1, T2):
return True
return self.isSubtree(T1.left, T2) or self.isSubtree(T1.right, T2)
def isSameTree(self, p, q):
if p is None and q is None:
return True
if p is None or q is None or p.val!=q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)