题目:https://www.nowcoder.com/ta/coding-interviews?query=&asc=true&order=&page=3
从上到下按层打印二叉树,与之前不同的是:同一层节点从左至右顺序打印(输出),每一层打印(输出)一行。
理解:
这里,根据要求返回二维列表,容易知道,为了把二叉树的每一行单独打印到一行,用列表存储每一层的节点值:[ [ ], [ ], [ ], …, [ ] ],第几层对应第几个子序列。
1 2 3 4 5 class TreeNode : def __init__ (self, x ): self .val = x self .left = None self .right = None
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution1 : def Print (self,pRoot ): result = [] self .level(pRoot, 0 , result) return result def level (self, root, level, result ): if not root: return None if level == len (result): result.append([]) 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 20 21 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
1 2 3 method = Solution1() answer = method.Print(root) answer
[[8], [6, 10], [5, 7, 9, 11], [12, 13]]
参考:
1.https://blog.csdn.net/fuxuemingzhu/article/details/79725053
2.https://blog.csdn.net/qq_18254385/article/details/94736589