1. 程式人生 > 實用技巧 >資料結構與演算法(22)——樹

資料結構與演算法(22)——樹

樹是一種基本的“非線性”資料結構。基本術語

節點Node

邊Edge

根Root:樹中唯一一個沒有入邊的節點

路徑Path:由邊依次連線在一起的節點有序表

子節點Children:入邊均來自同一個節點的若干節點

父節點Paren:一個節點是其所有邊所連線節點的父節點。

兄弟節點Sibling:具有同一個父節點的節點之間的節點稱為兄弟節點。

子樹Subtree:一個節點和其所有子孫節點,以及相關邊的集合。

葉節點Leaf:沒有子節點的節點稱為葉節點

層級Level:從根節點開始到達一個節點的路徑, 所包含的邊的數量,稱為這個節點的層級。 如D的層級為2,根節點的層級為0

高度:樹中所有節點的最大層級稱為樹的高度 ,如圖所示樹的高度為2

二叉樹:其中一個節點被設定為根; 每個節點n(除根節點),都恰連線一 條來自節點p的邊,p是n的父節點; 每個節點從根開始的路徑是唯一的,如果每個節點最多有兩個子節點, 這樣的樹稱為“二叉樹”

  • 樹的應用

檔案系統、HTML文件(巢狀標記)、域名體系。

  • 實現樹:巢狀列表法

以右圖的示例,一個6節點的二叉樹 根是myTree[0],左子樹myTree[1],右子樹 myTree[2] 。

巢狀列表法的優點 子樹的結構與樹相同,是一種遞迴資料結構 很容易擴充套件到多叉樹,僅需要增加列表元素即可

函式定義:

BinaryTree建立僅有根節點的二叉樹

insertLeft/insertRight將新節點插入樹中作為其直接的左/右子節點

get/setRootVal則取得或返回根節點

getLeft/RightChild返回左/右子樹

#樹的巢狀實現
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 grtRootVal(root): return root[0] def setRootVal(root, newVal): root[0] = newVal def getLeftChild(root): return root[1] def getRightChild(root): return root[2] r = BinaryTree(3) insertLeft(r, 4) insertLeft(r, 5) insertRight(r,6) insertRight(r,7) l = getLeftChild(r) rl = getRightChild(r) print("line1:", l) print("right line:", rl) print("root line:", r) setRootVal(l, 9) print("line2:", r) print("left sub tree:", getLeftChild(l)) insertLeft(l, 11) print("line3:",r) print(getRightChild(getRightChild(r)))

輸出

line1: [5, [4, [], []], []]
right line: [7, [], [6, [], []]]
root line: [3, [5, [4, [], []], []], [7, [], [6, [], []]]]
line2: [3, [9, [4, [], []], []], [7, [], [6, [], []]]]
left sub tree: [4, [], []]
line3: [3, [9, [11, [4, [], []], []], []], [7, [], [6, [], []]]]
[6, [], []]

Process finished with exit code 0