关注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