Python数据结构二叉树及其广度优先搜索

戏子无情 提交于 2019-12-02 11:15:26

前言

  关于Python编程,很多人说,Python实现不了数据结构,Python没有指针。其实,说过那句的人更应该好好学习Python。仔细阅读本文之后,读者能够使用Python实现基本的数据结构。

  以下列二叉树为例

  在使用二叉树的过程中,我们又常使用一些算法完成对树的遍历,比如广度优先搜索算法。
算法过程:

1.将根节点放入队列中

2.从队列中取出第一个元素,将队列中的第一个元素弹出

3.将所取得元素的全部节点加入队列中

4.判断队列是否为空

     a. 若是,则结束

     b.若不是,则跳到第二步

  了解了二叉树和广度优先搜索算法,那么我们用Python来实现他们吧

#结点类
class Node():
    def __init__(self, data=None):
        self.data = data
        self.left = None
        self.right = None
 
#二叉树
class Tree():
    def __init__(self):
        self.root = Node()
 
    def add(self, data):
        # 为树加入节点
        node = Node(data)
        if self.root.data == None:  # 如果树为空,就对根节点赋值
            self.root = node
        else:
            _ = []
            treeNode = self.root
            _.append(treeNode)
            while _:
                treeNode = _.pop(0)
                if not treeNode.left:
                    treeNode.left = node
                    return
                elif not treeNode.right:
                    treeNode.right = node
                    return
                else:
                    _.append(treeNode.left)
                    _.append(treeNode.right)
    #广度优先搜索                  
    def BFS(self,root= None):
        if root == None:
            root = self.root
        queue = []
        queue.append(root)
 
        while queue:
            now_node = queue.pop(0)
            print(now_node.data)
            if now_node.left != None:
                queue.append(now_node.left)
            if now_node.right != None:
                queue.append(now_node.right)
 
    
if __name__ == '__main__':
    datas = [8,3,10,1,6,14,4,7,13]
    tree = Tree() 
    for data in datas:
        tree.add(data)
 
    print('递归实现前序遍历:')
    tree.BFS()

  更多内容敬请期待下一篇,Python数据结构,队列与深度优先搜索

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!