题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def levelOrder(root: TreeNode) -> List[List[int]]: # 首先判断二叉树是否为空,空树没有遍历结果 res = [] if not root: return res # 队列存储,进行层次遍历 # 建立辅助队列,根节点首先进入队列。 q = queue.Queue() q.put(root) # 记录当前为空 cur = None # 判断队列是否为空 while not q.empty(): # row用于记录二叉树的某一行 row = [] n = q.qsize() # 因先进入的是根节点,故每层节点多少,队列大小就是多少 for i in range(n): cur = q.get() row.append(cur.val) # 若是左右孩子存在,则存入左右孩子作为下一个层次 if cur.left: q.put(cur.left) if cur.right: q.put(cur.right) # 访问完这一层的元素后,将这个一维数组加入二维数组中,再访问下一层。 res.append(row) return res if __name__ == '__main__': root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.left = TreeNode(6) root.right.right = TreeNode(7) result = levelOrder(root) print(result)