Binary Tree Level Order Traversal II @ LeetCode (Python)
kitt
posted @ 2014年3月05日 00:12
in LeetCode
, 2317 阅读
同Binary Tree Level Order Traversal题目一样,也需要一个dict来记录层的信息。dict[1] = [9, 20]。
# 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 preOrder(self, root, level): if level not in Solution.L: Solution.L[level] = [root.val] else: Solution.L[level].append(root.val) if root.left: self.preOrder(root.left, level + 1) if root.right: self.preOrder(root.right, level + 1) def levelOrderBottom(self, root): res = [] if root == None: return res Solution.L = {} self.preOrder(root, 0) for i in sorted(Solution.L.keys(), reverse = True): res.append(Solution.L[i]) return res