其实和102. Binary Tree Level Order Traversal这题几乎一样的思路和解法。
不赘述,直接给代码。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
result = []
if root is None:
return result
queue = [root]
while len(queue):
length = len(queue)
level = []
for i in range(length):
p = queue.pop(0)
level.append(p.val)
if p.left:
queue.append(p.left)
if p.right:
queue.append(p.right)
result.insert(0, level)
return result
网友评论