【数据结构与算法题目集】(Python实现)7-3 树的同构

测试点全部通过,卡点在判断是否同构的函数里面,关于判空,这个我自己写的代码因为是用-1表示空,因此在递归的时候几个if统一用-1来判空,而不用None,否则就会导致测试点不通过;

class TreeNode:
    def __init__(self,val,left=None,right=None,parent=None):
        self.val = val
        self.leftChild = left
        self.rightChild = right

def generateTree(n):
    if n==0:return TreeNode(None),-1
    nodeList = []
    root = -1
    check = [0]*n
    for _ in range(n):
        s = list(input().split())
        t = TreeNode(s[0])
        if s[1]!='-':
            t.leftChild=int(s[1])
            check[t.leftChild]=1
        else:
            t.leftChild=-1
        if s[2]!='-':
            t.rightChild=int(s[2])
            check[t.rightChild]=1
        else:
            t.rightChild=-1
        nodeList.append(t)
    for i in range(n):
        if check[i]==0:
            root = i
            break
    return nodeList,root
n1=int(input())
T1,r1=generateTree(n1)
n2=int(input())
T2,r2=generateTree(n2)

def isOmorphic(r1,r2):
    if r1==-1 and r2==-1: return True
    if (r1!=-1 and r2==-1) | (r1==-1 and r2!=-1):
        return False
    if T1[r1].val!=T2[r2].val:
        return False
    if T1[r1].leftChild==-1 and T2[r2].leftChild==-1:
        return isOmorphic(T1[r1].rightChild,T2[r2].rightChild)
    if T1[r1].leftChild!=-1 and T2[r2].leftChild!=-1 and T1[T1[r1].leftChild].val==T2[T2[r2].leftChild].val:
        return isOmorphic(T1[r1].leftChild,T2[r2].leftChild) and isOmorphic(T1[r1].rightChild,T2[r2].rightChild)
    else:
        return isOmorphic(T1[r1].leftChild,T2[r2].rightChild) and isOmorphic(T1[r1].rightChild,T2[r2].leftChild)

if isOmorphic(r1,r2):
    print('Yes')
else:
    print('No')

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