檢驗一顆樹是不是另一顆樹的子結構

獨鹿發表於2018-04-23

思路:遍歷樹,使用遞迴方法。1.先判斷節點值是否相等,如果相等則繼續判斷他們的子樹是否相等;2.如果不相等則判斷他們的子樹是否相等。這樣一直遞迴。退出條件為知道子樹到葉節點了,

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_)

相關文章