python樹的同構(gòu)學(xué)習(xí)筆記
一、題意理解
給定兩棵樹T1和T2。如果T1可以通過若干次左右孩子互換就變成T2,則我們稱兩棵樹是“同構(gòu)的”?,F(xiàn)給定兩棵樹,請你判斷它們是否是同構(gòu)的。

輸入格式:輸入給出2棵二叉樹的信息:
先在一行中給出該樹的結(jié)點樹,隨后N行
第i行對應(yīng)編號第i個結(jié)點,給出該結(jié)點中存儲的字母、其左孩子結(jié)點的編號、右孩子結(jié)點的編號
如果孩子結(jié)點為空,則在相應(yīng)位置給出“-”
如下圖所示,有多種表示的方式,我們列出以下兩種:


二、求解思路
搜到一篇也是講這個的,但是那篇并沒有完全用到單向鏈表的方法,所以研究了一下,寫了一個是完全用單向鏈表的方法:
其實應(yīng)該有更優(yōu)雅的刪除整個單向列表的方法,比如頭設(shè)為none,可能會改進(jìn)下?
# python語言實現(xiàn)
L1 = list(map(int, input().split()))
L2 = list(map(int, input().split()))
# 節(jié)點
class Node:
def __init__(self, coef, exp):
self.coef = coef
self.exp = exp
self.next = None
# 單鏈表
class List:
def __init__(self, node=None):
self.__head = node
# 為了訪問私有類
def gethead(self):
return self.__head
def travel(self):
cur1 = self.__head
cur2 = self.__head
if cur1.next != None:
cur1 = cur1.next
else:
print(cur2.coef, cur2.exp, end="")
return
while cur1.next != None:
print(cur2.coef, cur2.exp, end=" ")
cur1 = cur1.next
cur2 = cur2.next
print(cur2.coef, cur2.exp, end=" ")
cur2 = cur2.next
print(cur2.coef, cur2.exp, end="")
# add item in the tail
def append(self, coef, exp):
node = Node(coef, exp)
if self.__head == None:
self.__head = node
else:
cur = self.__head
while cur.next != None:
cur = cur.next
cur.next = node
def addl(l1, l2):
p1 = l1.gethead()
p2 = l2.gethead()
l3 = List()
while (p1 is not None) & (p2 is not None):
if (p1.exp > p2.exp):
l3.append(p1.coef, p1.exp)
p1 = p1.next
elif (p1.exp < p2.exp):
l3.append(p2.coef, p2.exp)
p2 = p2.next
else:
if (p1.coef + p2.coef == 0):
p1 = p1.next
p2 = p2.next
else:
l3.append(p2.coef + p1.coef, p1.exp)
p2 = p2.next
p1 = p1.next
while p1 is not None:
l3.append(p1.coef, p1.exp)
p1 = p1.next
while p2 is not None:
l3.append(p2.coef, p2.exp)
p2 = p2.next
if l3.gethead() == None:
l3.append(0, 0)
return l3
def mull(l1, l2):
p1 = l1.gethead()
p2 = l2.gethead()
l3 = List()
l4 = List()
if (p1 is not None) & (p2 is not None):
while p1 is not None:
while p2 is not None:
l4.append(p1.coef * p2.coef, p1.exp + p2.exp)
p2 = p2.next
l3 = addl(l3, l4)
l4 = List()
p2 = l2.gethead()
p1 = p1.next
else:
l3.append(0, 0)
return l3
def L2l(L):
l = List()
L.pop(0)
for i in range(0, len(L), 2):
l.append(L[i], L[i + 1])
return l
l1 = L2l(L1)
l2 = L2l(L2)
l3 = List()
l3 = mull(l1, l2)
l3.travel()
print("")
l3 = List()
l3 = addl(l1, l2)
l3.travel()
以上就是本次介紹的全部內(nèi)容知識點,相關(guān)內(nèi)容可以參閱下方知識點,感謝大家對腳本之家的支持。
相關(guān)文章
python傳到前端的數(shù)據(jù),雙引號被轉(zhuǎn)義的問題
這篇文章主要介紹了python傳到前端的數(shù)據(jù),雙引號被轉(zhuǎn)義的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
python+selenium實現(xiàn)簡歷自動刷新的示例代碼
這篇文章主要介紹了python+selenium實現(xiàn)簡歷自動刷新的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05

