17. substructure tree
problem:
Two binary inputs A, B, B is judged not substructure A's. (Ps: we agreed empty tree is not a tree any substructure)
solve:
thought:
We just need to find out whether there is a value equal to a node and b-node, and then recursively view the left and right nodes are equal to
python code:
# -*- 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
if pRoot1==None or pRoot2==None:
return False
return self.istree(pRoot1,pRoot2) or self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)
def istree(self,p1,p2):
if p2==None:
return True
if(p1==None or p1.val!=p2.val):
return False
return self.istree(p1.left,p2.left) and self.istree(p1.right,p2.right)