Determine if one tree is a subtree of another tree

topic

Determine whether b is a subtree of a

Ideas

First judge whether the root nodes are the same, if they are the same, then recursively judge the left and right subtrees, if they are not the same, use the root node of b to compare the left and right subtrees of a.

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):
        result = False
        if  pRoot2 is None or pRoot1 is None:
            return False
        if pRoot1.val == pRoot2.val:
            result =  self.issubtree(pRoot1,pRoot2)
        if result is False:
            return self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)
        return result
    def issubtree(self,node1,node2):
        if node2 is None:
            return True
        if node1 is None:
            return False
        if node1.val != node2.val:
            return False
        else:
            return self.issubtree(node1.left, node2.left) and self.issubtree(node1.right, node2.right)

Guess you like

Origin blog.csdn.net/aaaqqq1234/article/details/107959538