• 【算法】二叉树的广度遍历


    广度优先遍历的核心思想如下:从根节点开始遍历,然后遍历其子节点,再从左至右的,依次遍历其孙子节点的,以此类推,直到完成整颗二叉树的遍历。

             50

       20         60

    15  30            70

    以如上的二叉树为例,其广度优先遍历的顺序是:50、20、60、15、30、70。

    在代码中,我们使用队列进行广度优先遍历,先把根节点放入队列,利用队列的先进先出原则,访问队列中取出的节点,并分别把左子节点和右子节点放入队列,循环下去,直到队列为空。

    #encoding=utf-8
    
    from queue import Queue
    
    class TreeNode(object):
        def __init__(self,val,left=None,right=None):
            self.val=val
            self.left=left
            self.right=right
    
    class BinaryTree(object):
        def __init__(self,root=None):
            self.root=root #这里传入的是创建好的Tree
            #print(root.val)
    
        def breathSearth(self):
            if self.root==None:
                return None
            retlist=[]
            queue=Queue()
            queue.put(self.root) #用队列的方式,先进先出,先将Tree从顶到底一次放进去,然后调用queue.get()方法,依次取出来存到retlist中
            while queue.empty() is not True:
                node=queue.get()
                retlist.append(node.val)
                if node.left!=None: #如果左节点和右节点不为空,再依次放到队列中,while循环再取出来存到retlist中
                    queue.put(node.left) 
                if node.right!=None:
                    queue.put(node.right)
            return retlist
    
    if __name__=="__main__":
        #创建二叉树
        rootNode=TreeNode(50)
        rootNode.left=TreeNode(20,left=TreeNode(15),right=TreeNode(30))
        rootNode.right=TreeNode(60,right=TreeNode(70))
    
        #实例化
        tree=BinaryTree(rootNode) #把创建好的二叉树传进去
        retlist=tree.breathSearth()
        print(retlist)
  • 相关阅读:
    Spring总结
    基于LSM的KeyValue数据库实现WAL篇
    基于LSM的KeyValue数据库实现稀疏索引篇
    微服务策略
    linux安装python centos
    python list 差集
    MySQL主从复制原理
    mac、windows 配置python国内镜像源
    微服务介绍
    vim中跳到第一行和最后一行
  • 原文地址:https://www.cnblogs.com/jingsheng99/p/9819733.html
Copyright © 2020-2023  润新知