Binary tree decision

# -*- 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
        else:
            res0 = self.HasSubtree(pRoot1.left,pRoot2)
            res1 = self.HasSubtree (pRoot1.right, pRoot2)
            res2 = self.isSubtree(pRoot1,pRoot2)
            
            if res0 == True or res1 == True or res2 == True:
                return True
            else:
                return False
    def isSubtree(self,pRoot1,pRoot2):
        if pRoot2 == None:
            return True
        if pRoot1 == None:
            return False
        
        if pRoot1.val == pRoot2.val:
            res0 = self.isSubtree(pRoot1.left,pRoot2.left)
            res1 = self.isSubtree(pRoot1.right,pRoot2.right)
            
            if res0 == True and res1 == True:
                return True
        return False

The determination of binary subtree is divided into two steps. One is to determine whether the node and the root node of the subtree overlap. If they overlap, start the next step:

The second step is to recursively determine whether each child node is the same, if it is the same, return True

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325588091&siteId=291194637