二叉树的层序遍历有两种方法,分别是递归和队列,我看上面的大佬都用的递归,我来个队列的吧
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param root TreeNode类
# @return int整型二维数组
#
class Solution:
def levelOrder(self , root: TreeNode) -> List[List[int]]:
# write code here
res = []
tree_list = []
if root == None:
return res
tree_list.append(root)
while len(tree_list) > 0:
level_number = len(tree_list)
tmp = []
for i in range(level_number):
# 记录每一层的节点个数
node = tree_list.pop(0)
tmp.append(node.val)
if node.left:
tree_list.append(node.left)
if node.right:
tree_list.append(node.right)
res.append(tmp)
return res