[Python] 數據結構與算法筆記(樹與圖)

4. 樹

非線性結構

4.1 樹的定義

在這裏插入圖片描述

4.2 樹的實現

4.2.1 嵌套列表法

在這裏插入圖片描述

myTree = [
    'a',
    ['b',
     ['d', [], []],
     ['e', [], []] ],
    ['c',
     ['f',[],[]],
     [] ]
]

在這裏插入圖片描述

def BinaryTree(r):
    return [r, [], []]

def insertLeft(root, newBranch):
    t = root.pop(1)
    if len(t) > 1:
        root.insert(1, [newBranch, t, []])
    else:
        root.insert(1, [newBranch, [], []])
    return root

def insertRight(root, newBranch):
    t = root.pop(2)
    if len(t) > 1:
        root.insert(2, [newBranch, [], t])
    else:
        root.insert(2, [newBranch, [], []])
    return root

def getRootVal(root):
    return root[0]

def setRootVal(root, newVal):
    root[0] = newVal

def getLeftChild(root):
    return root[1]

def getRightChild(root):
    return root[2]

e.g.

r = BinaryTree(3)
insertLeft(r,4)
insertLeft(r,5)
insertRight(r,6)
insertRight(r,7)
l = getLeftChild(r)
print(l)

setRootVal(l, 9)
print(r)

insertLeft(l, 11)
print(r)
print(getRightChild(getRightChild(r)))

[5, [4, [], []], []]
[3, [9, [4, [], []], []], [7, [], [6, [], []]]]
[3, [9, [11, [4, [], []], []], []], [7, [], [6, [], []]]]
[6, [], []]
在這裏插入圖片描述

4.2.2 節點鏈接法

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

4.3 樹的應用——表達式解析

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

4.4 樹的遍歷

在這裏插入圖片描述
在這裏插入圖片描述

4.5 優先隊列和二叉堆

4.5.1 優先隊列和二叉堆基本概念

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

4.5.2 二叉堆的Python實現

在這裏插入圖片描述
insert
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
del
在這裏插入圖片描述

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

4.5 二叉查找樹及操作

在這裏插入圖片描述

在這裏插入圖片描述

5. 圖

內容丟失,博主有點小難受,暫時不更。
溜了溜了, 大家一起頭禿,一起debug~

最後

感謝北京大學陳斌老師的《數據結構與算法Python版》,來源慕課。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章