Python數據結構 - 樹、圖

Python數據結構

  • 鄰接表法 adjacency list. 對於每個結點,用列表(list)來存儲它的臨接結點. 一個有向圖的列子:
twitter_graph = dict()
twitter_graph['Bob'] = ['Jack', 'Nox', 'Willy']
twitter_graph['Jack'] = ['Amy', 'Nox']
twitter_graph['Amy'] = ['Willy', 'Bob']
twitter_graph['Willy'] = ['Bob']
twitter_graph['Nox'] = []
  • 鄰接矩陣(adjacency matrix)。鄰接矩陣的行數和列數都等於結點數。對於矩陣中的每個單元,true 代表結點間存在關係,false 代表不存在關係。在 Python 中,我們可以用兩級列表模擬一個這樣的矩陣。
num_nodes = len(twitter_graph.keys())
# I初始化所有的邊爲 False
twitter_graph_matrix = [[False for _ in range(num_nodes)] for _ in range(num_nodes)]
ids = dict()
# 爲每個結點分配一個 id
for i, node in enumerate(sorted(twitter_graph.keys())):
    ids[node] = i
# 根據鄰接表填充鄰接矩陣
for node in twitter_graph.keys():
    for target in twitter_graph[node]:
        twitter_graph_matrix[ids[node]][ids[target]] = True
twitter_graph_matrix

二叉搜索樹

二叉搜索樹(BST)是二叉樹,其中每個結點的值(鍵)大於或等於其左子樹中的所有值,並且小於其右子樹中的所有值。

  • 一個簡單的樹結點類
class TreeNode:
    def __init__(self, data):
        self.data = data
        self.leftChild = None
        self.rightChild = None
  • 二叉樹的實現:
class BinarySearchTree:
    def __init__(self, root=None):
        self.root = root
        
    # Find the node with the minimum value    
    def find_min(self):
        if self.root is None:
            return None
        current = self.root
        while current.leftChild is not None:
            current = current.leftChild
        return current
    
    # Find the node with the maximum value
    def find_max(self):
        if self.root is None:
            return None
        current = self.root
        while current.rightChild is not None:
            current = current.rightChild
        return current
    
    # Insert a node with data into the BST
    def insert(self, data):
        node = TreeNode(data)
        if self.root is None:
            self.root = node
        else:
            current = self.root
            while True:
                if data < current.data:
                    if current.leftChild is None:
                        current.leftChild = node
                        return 
                    current = current.leftChild
                else:
                    if current.rightChild is None:
                        current.rightChild = node
                        return 
                    current = current.rightChild
    
    # Delete a node with data from the BST
    # Not implemented yet.
    # This function is a bit tricky; we need to find the node with data first;
    # then based on how many children it has, proceeds with different actions;
    # 0 or 1 child should be easy, while 2 children is not trivial;
    # need to find from its right child the node with smallest value that is
    # bigger than the target's value
    def delete(self, data):
        # your code
        pass
    
    # Search for the node with data
    def search(self, data):
        current = self.root
        while current is not None:
            if current.data == data:
                return current
            current = current.leftChild if data < current.data else current.rightChild
        return current
        
def mid_traverse(root): 
    if root is None:
        return  
    mid_traverse(root.leftChild)  
    print(root.data,' ', end='')  
    mid_traverse(root.rightChild) 
  • 實踐:創建一個二叉樹,查找最大值,最小值,搜索數據
bst = BinarySearchTree()
for num in (7, 5, 9, 8, 15, 16, 18, 17):
    bst.insert(num)
max_node = bst.find_max() # 搜索最大值
min_node = bst.find_min() # 搜索最小值
print(f"Max node: {max_node.data}")
print(f"Min node: {min_node.data}")
# 搜索數據
for n in (17, 3, -2, 8, 5):
    if bst2.search(n) is not None:
        print(f"{n} found in the binary search tree! :D")
    else:
        print(f"{n} not found in the tree! :(")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章