难度:中等
题目描述:
思路总结:看到这题,不知是受到什么毒害,首先想到了队列和栈,但发现得用两个分别存当前和子节点,遂放弃,看官方题解,还是两种方法,递归和迭代。
题解一:(递归)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root == None:return []
res = []
def helper(node, level):
if len(res) == level:
res.append([])
res[level].append(node.val)
if node.left:
helper(node.left, level+1)
if node.right:
helper(node.right, level+1)
helper(root, 0)
return res
题解一结果:
题解二:(迭代)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
#思路:利用队列先进先出性,再加上【每次计算上一层长度】。
if root == None:return []
res = []
queue = deque([root, ])
level = 0
while queue:
llen = len(queue)
res.append([])
while llen > 0:
node = queue.popleft()
llen -= 1
res[level].append(node.val)
if node.left:queue.append(node.left)
if node.right:queue.append(node.right)
level += 1
return res
题解二结果: