
二叉树的层序遍历,本质就是广度遍历有向图。都要用到队列。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
deque = []
if not root:
return []
new = [root]
while len(new):
temp = new.pop(0)
deque.append(temp.val)
if temp.left:
new.append(temp.left)
if temp.right:
new.append(temp.right)
return deque
本文深入探讨了二叉树的层序遍历算法,即广度优先搜索的应用。通过使用队列数据结构,文章详细解释了如何从根节点开始,按层次顺序访问所有节点的过程。
1336

被折叠的 条评论
为什么被折叠?



