题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
关注python中queue的用法
import queue
class Solution:
def levelOrder(self , root: TreeNode) -> List[List[int]]:
# write code here
res = []
if not root:
return res
q = queue.Queue()
q.put(root)
while not q.empty():
q_len = q.qsize()
res_q = []
for _ in range(q_len):
temp = q.get()
res_q.append(temp.val)
if temp.left:
q.put(temp.left)
if temp.right:
q.put(temp.right)
res.append(res_q)
return res