Binary Tree Level Order Traversal (Python)
kitt
posted @ 2014年2月09日 21:33
in LeetCode
, 2337 阅读
先遍历,记录下每个节点在第几层,然后按层输出。
# 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 in Solution.L: Solution.L[level].append(root.val) else: Solution.L[level] = [root.val] if root.left: self.preOrder(root.left, level + 1) if root.right: self.preOrder(root.right, level + 1) return def levelOrder(self, root): res = [] if root == None: return res Solution.L = {} self.preOrder(root, 0) for i in sorted(Solution.L.keys()): res.append(Solution.L[i]) return res