Check if B is Subtree of A
Last updated
Last updated
{8,8,#,9,#,2,#,5},{8,9,#,2}true# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
res = False
if pRoot1 and pRoot2:
if pRoot1.val == pRoot2.val:
# start from current node1 and root of B to check
res = self.sametree(pRoot1, pRoot2)
if not res:
# if doesn't match, start from left subtree, or right
# subtree to match subtree of A and tree B
res = self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2)
return res
def sametree(self, node1, node2):
if (node2 and not node1):
# if node2 still exist, but node1 doesn't exist
# then node2 is not subtree of node1
return False
if not node2:
#if node2, B, already checked entirely, but node1 A still
# exist, then B is subtree, part of A
return True
if node1.val != node2.val:
return False
f1= self.sametree(node1.left, node2.left) and self.sametree(node1.right, node2.right)
return f1