單雙向連結及二元樹

單向連結

import numpy as np
class Node():
def __init__(self):
self.next=None
self.value=0
if __name__=='__main__':
n=10
nums=np.random.randint(1,100,n)
print(f'原始資料 : {nums}')
root=Node()
index=root
#建立單向連結
for n in nums:
index.value=n
index.next=Node()
index=index.next
#正向列印
index=root
print('正向列印 : ', end='')
while index.next !=None:
print(f'{index.value} ', end='')
index=index.next
print()
結果 :
原始資料 : [78 28 26 6 68 90 83 18 69 79]
正向列印 : 78 28 26 6 68 90 83 18 69 79

雙向連結

import numpy as np
class Node():
def __init__(self):
self.next=None
self.prev=None
self.value=0
if __name__=='__main__':
n=10
nums=np.random.randint(1,100,n)
print(f'原始資料 : {nums}')
root=Node()
index=root
#建立雙向連結
for n in nums:
index.value=n
index.next=Node()
index.next.prev=index
index=index.next
#正向列印
index=root
print('正向列印 : ', end='')
while index.next !=None:
print(f'{index.value} ', end='')
index=index.next
print()

#反向列印
while index.next!=None:
index=index.next
print('反向列印 : ', end='')
while index.prev !=None:
print(f'{index.prev.value} ', end='')
index=index.prev
print()
結果 :
原始資料 : [82 43 49 43 73 55 49 21 50 90]
正向列印 : 82 43 49 43 73 55 49 21 50 90
反向列印 : 90 50 21 49 55 73 43 49 43 82

二元樹規則

二元樹(Binary Tree)是近代搜索引擎的演算法, 效能非常優異. 但蠻耗記憶体的. 需採用Recursive進行運算。

元樹的規則如下 :

🔒 底下內容僅限會員閱讀。

立即登入

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *