【数据结构与算法题目集】(Python实现)7-4 是否同一棵二叉搜索树

class TreeNode:
    def __init__(self,val,left=None,right=None):
        self.val = val
        self.left = left
        self.right = right
        self.flag = 0
def insert(root,val):
    if not root:
        root = TreeNode(val)
    else:
        if val>root.val:
            root.right = insert(root.right,val)
        else:
            root.left = insert(root.left,val)
    return root                 
def buildTree(stdList):
    root = TreeNode(stdList[0])
    for i in range(1,len(stdList)):
        insert(root,stdList[i])
    return root
def check(root,v):
    if root.flag:
        if v<root.val:
            return check(root.left,v)
        elif v>root.val:
            return check(root.right,v)
        else:
            return 1
    else:
        if v==root.val:
            root.flag = 1
            return 0
        return 1
def reset(root):
    if root.left:
        reset(root.left)
    if root.right:
        reset(root.right)
    root.flag = 0
def isSameBinarySearchTree(root,seqList):
    res = []
    for seq in seqList:
        Flag = 0  # 0表示目前还是一致
        for i in range(len(seq)):
            if check(root,seq[i]):
                Flag = 1
        if Flag:
            res.append('No')
        else:
            res.append('Yes')
        reset(root)
    return res

while True:  # 输入数据
    inpt = list(map(int,input().split()))
    if inpt[0]==0:
        break
    else:
        N=inpt[0]
        L=inpt[1]
        stdList = list(map(int,input().split()))  # 输入初始插入序列
        stdTree = buildTree(stdList)
        seqList = []  # 要检查的序列集合
        for i in range(L):
            seqList.append(list(map(int,input().split())))
        res = isSameBinarySearchTree(stdTree,seqList)
        for rs in res:
            print(rs)

以上方法参考mooc浙大数据结构
其他思路可以看 这个博客

你可能感兴趣的:(#,PTA)