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! :(")

猜你喜欢

转载自blog.csdn.net/FengKuangXiaoZuo/article/details/88787953
今日推荐