目錄
- 一、題意理解
- 二、求解思路
更新、更全的《數據結構與算法》的更新網站,更有python、go、人工智能教學等著你:
一、題意理解
給定兩棵樹T1和T2。如果T1可以通過若干次左右孩子互換就變成T2,則我們稱兩棵樹是“同構的”。現給定兩棵樹,請你判斷它們是否是同構的。
輸入格式: 輸入給出2棵二叉樹的信息:
-
先在一行中給出該樹的結點樹,隨后N行
- 第i行對應編號第i個結點,給出該結點中存儲的字母、其左孩子結點的編號、右孩子結點的編號
-
如果孩子結點為空,則在相應位置給出“-”
如下圖所示,有 多種表示 的方式,我們列出以下兩種:
二、求解思路
搜到一篇也是講這個的,但是那篇并沒有完全用到單向鏈表的方法,所以研究了一下,寫了一個是完全用單向鏈表的方法:
其實應該有更優雅的刪除整個單向列表的方法,比如頭設為none,可能會改進下?
# python語言實現
L1 = list(map(int, input().split()))
L2 = list(map(int, input().split()))
# 節點
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()
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
