Check if a tree is a substructure of another tree

Idea: traverse the tree, use recursive method. 1. First determine whether the node values ​​are equal, and if they are equal, continue to determine whether their subtrees are equal; 2. If they are not equal, determine whether their subtrees are equal. This keeps recurring. The exit condition is to know that the subtree has reached the leaf node,

class BinaryTreeNode(object):
    def __init__(self,data,left=None,right=None):
        self.data = data
        self.left = left
        self.right = right
A = BinaryTreeNode("A")
B = BinaryTreeNode("B")
C = BinaryTreeNode("C")
D = BinaryTreeNode("D")
E = BinaryTreeNode("E")
F = BinaryTreeNode("F")
G = BinaryTreeNode("G")
A.data = 8
B.data = 8
C.data = 7
D.data = 9
E.data = 2
F.data = 4
G.data = 7

A.left = B
A.right = C
B.left = D
B.right=E
E.left = F
E.right = G

A_ = BinaryTreeNode("A_")
B_ = BinaryTreeNode("B_")
C_ = BinaryTreeNode("C_")
A_.data = 8
B_.data = 9
C_.data = 2
A_.left = B_
A_.right = C_
def isSub(tree1,tree2):
    if tree2 is None:
        return True
    if tree1 is None:
        return False
    if tree1.data != tree2.data:
        return False
    return isSub(tree1.left,tree2.left) and isSub(tree1.right,tree2.right)

def hashB(tree1,tree2):
    r = False
    if tree1 is None or tree2 is None:
        return False
    if tree1.data == tree2.data:
        r = isSub(tree1,tree2)
    if not r:
        r = hashB(tree1.left,tree2)
    if not r:
        r = hashB(tree1.right,tree2)
    return r


print "---",hashB(A,A_)

Guess you like

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