classSolution1: # 返回二维列表[[1,2],[4,5]] defPrint(self,pRoot): result = [] self.level(pRoot, 0, result) return result deflevel(self, root, level, result): ifnot root: returnNone if level == len(result): result.append([])#为每一层建立子序列, #实际上这里需要追加子序列的情况:1.根节点时level=0=len(result),建立子序列; #2.假如左节点成立的话,左节点时level+1=len(result),需要建立子序列。而此后在判断同层右节点时,level已经变化多次,不再需要建立子序列。 #3.假如左节点不成立的话,在判断右节点时level+1=len(result),需要建立子序列。 result[level].append(root.val)#将节点值放入对应的子序列 if root.left: self.level(root.left, level+1, result)#左节点 if root.right: self.level(root.right, level+1, result)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
root = TreeNode(8) a = TreeNode(6) b = TreeNode(10) c = TreeNode(5) d = TreeNode(7) e = TreeNode(9) f = TreeNode(11) g = TreeNode(12) h = TreeNode(13) root.left = a root.right = b a.left = c a.right = d b.left = e b.right = f d.left = g d.right = h