python数据结构与算法练习-二叉树层序遍历

python数据结构与算法练习-二叉树层序遍历问题

    • 层序遍历
    • python实现

层序遍历

二叉树的层序遍历是从树的每一层开始从左到右挨个访问树的节点。这里采用队列的思想,先将根节点入队列,然后出队并查看当前节点是否存在左孩子和右孩子,如果存在,则递归调用。

python实现

from collections import deque
def level_order(root):
    queue = deque()
    queue.append(root)
    while len(queue)>0:
        node = queue.popleft()
        print(node,end='')
        if node.left:
            level_order(root.left)
        if node.right:
            level_order(root.right)
            

知识点记录。

你可能感兴趣的:(数据结构,算法,python)