Question: https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/
Question Name: Binary Tree Level Order Traversal II
Nearly the same as the Binary Tree Level Order Traversal. We only need to reverse the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def levelOrderBottom(self, root): if root == None: return [] # In the first stage, we store hte nodes (not their value). result = [] nextLayer = [root] while len(nextLayer) != 0: result.append(nextLayer) # Gather the nodes in the next deeper layer. nextLayer = [] for father in result[-1]: if father.left != None: nextLayer.append(father.left) if father.right != None: nextLayer.append(father.right) # In the second stage, we convert the nodes into their values. result = [[node.val for node in layer] for layer in result] return result[::-1] |