时间复杂度(O(n)),思想:队列层次遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import queue
class Solution:
def levelOrder(self, root: TreeNode) -> [[int]]:
if root == None :return []
r, q = [], queue.Queue()
q.put(root)
while q.empty() == False:
p = queue.Queue()
r.append([])
while q.empty() == False:
curr_node = q.get()
r[-1].append(curr_node.val)
if curr_node.left != None: p.put(curr_node.left)
if curr_node.right != None: p.put(curr_node.right)
q = p
return r