题目:https://www.nowcoder.com/ta/coding-interviews?page=3
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
考虑:跟之前按行打印二叉树的思路,先将二叉树按行分别存入二维列表,然后将特定的子列表翻转
列表翻转:
1.https://www.runoob.com/python3/python-reversing-list.html
2.https://www.runoob.com/python3/python-slicing-rotate-string.html
1 2 3 4 5 6 7 8 9 10 a=[1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ] print(a) d=a[::-1 ] print(a) c=a print(d) c.reverse() print(c) print(a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
1 2 3 4 5 6 def Reverse (lst) : lst.reverse() return lst a=[1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ] print(Reverse(a))
[9, 8, 7, 6, 5, 4, 3, 2, 1]
for循环步长:https://www.runoob.com/python3/python3-loop.html
1 2 3 4 5 res = [[8 ], [6 , 10 ], [5 , 7 , 9 , 11 ], [12 , 13 ]] for level in range(1 , len(res), 2 ): res[level] = res[level][::-1 ] print(res)
[[8], [10, 6], [5, 7, 9, 11], [13, 12]]
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 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 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Solution : def Print (self, pRoot) : if not pRoot: return [] result = [] level = 0 self.level(pRoot, level, result) for level in range(1 , len(result), 2 ): result[level] = result[level][::-1 ] 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 method = Solution() answer = method.Print(root) answer
[[8], [10, 6], [5, 7, 9, 11], [13, 12]]
参考:https://blog.csdn.net/fuxuemingzhu/article/details/79724959