# 【leetcode】102:二叉树的层序遍历

解答如下：

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: return []
#跟结点入queue
queue = [root]
res = []
while queue:
res.append([node.val for node in queue])
#存储当前层的孩子节点列表
ll = []
#对当前层的每个节点遍历
for node in queue:
#如果左子节点存在，入队列
if node.left:
ll.append(node.left)
#如果右子节点存在，入队列
if node.right:
ll.append(node.right)
#后把queue更新成下一层的结点，继续遍历下一层
queue = ll
return res

class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: return []
res = []
queue = [root]
while queue:
tmp = []
for _ in range(len(queue)):
node = queue.pop(0)
tmp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(tmp)
return res

def BFS(root):
if root:
res = []
queue = [root]
while queue:
currentNode = queue.pop(0)
res.append(currentNode.val)
if currentNode.left:
queue.append(currentNode.left)
if currentNode.right:
queue.append(currentNode.right)
return res

posted @ 2021-10-11 21:16  Geeksongs  阅读(6)  评论(0编辑  收藏  举报