107. 二叉树的层次遍历 II 和层序遍历一样,利用栈来层序遍历,只不过每层遍历完之后,把结果插入到list头部。
python # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: stack = [root] anss = [] while stack!=[]: ans = [] for _ in range(len(stack)): node = stack.pop(0) if node!=None: stack.append(node.left) stack.append(node.right) ans.append(node.val) if ans!=[]: anss.insert(0,ans[:]) return anss