python 数据结构与算法 day05 二叉树的广度优先遍历(层次遍历--横向)

1. 二叉树的广度优先遍历

class Node(object):
    """创建一个节点类"""
    def __init__(self,item):
        self.item=item  # 创建的能挂在树上的节点 得有一个data数据域 还得有两个左右节点指向左右子节点(因为实现的是二叉树,每个节点最多两个子节点)
        self.lchild=None  # 当前节点的左子节点
        self.rchild=None  # 当前节点的右子节点

class Tree(object):
    """构建二叉树"""
    def __init__(self):
        self.root=None  # 构建的一棵树首先得有一个根节点(就像链表有一个头节点self.__head)

    def add(self,item):
        """实现二叉树添加元素"""
        node=Node(item)
        queue=[]  # 队列(把当前树的所有节点都存放在队列中,然后挨个取出队列中的元素,判断该节点的做右子节点是否都存在,不存在就挂在当前节点的相应自节点位置上)
        if self.root is None:  # 如果当前树是一个空树 直接就把要添加的元素放在根节点上就好啦
            self.root=node
            return
        queue.append(self.root)  # 先把树的根节点放在队列中,也就是从根节点开始遍历
        while queue:
            cur_node=queue.pop(0) # queue队列存放的是当前树所有节点(没有被遍历过的) 然后挨个取出节点,遍历做右子节点
            if cur_node.lchild is None:
                cur_node.lchild=node
                return
            else:
                queue.append(cur_node.lchild)
            if cur_node.rchild is None:
                cur_node.rchild=node
                return
            else:
                queue.append(cur_node.rchild)
    def breadth_travel(self):
        """二叉树的广度优先遍历"""
        if self.root is None:  # 如果最开始是一个空树,广度优先遍历,没法遍历元素,所以直接返回ok
            return
        queue=[self.root]  # 对于二叉树不是空树的情况下,需要把当前树的所有节点都添加到队列中,然后遍历,首先把二叉树的根节点添加到队列中
        while queue:  
            cur_node=queue.pop(0)  # 首先取出根节点,然后后续的取出树中的其他节点
            print(cur_node.item)  # 打印出当前节点的元素值
            if cur_node.lchild is not None:  # 如果当前节点的左子节点非空,就把左子节点添加到需要遍历的队列queue中
                queue.append(cur_node.lchild)
            if cur_node.rchild is not None:
                queue.append(cur_node.rchild)


tree=Tree()
tree.add(2)
tree.add(1)
tree.add(4)
tree.add(3)
tree.breadth_travel()

运行结果:

总结:深度优先遍历又称为层次遍历,就是从根节点开始,依次找下一层的左子节点,右子节点,从左往右直至把该层遍历完,再继续下一层元素的遍历~

talk is cheap,show me the code
原文地址:https://www.cnblogs.com/xuanxuanlove/p/9953989.html