【题目要求】从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
【解题思路】队列实现/两个栈。跟按照之字形打印二叉树相比,省去了反转顺序(上一篇中direction的地方),同时注意每次调用子函数的时候不再是pop()(从结尾出),而是从头出(pop(0))
【第一次代码】
class Solution: def Zprint(self, list_out,stack): if stack: temp_stack = [] temp_list = [] while stack: root = stack.pop(0) if root.left: temp_list.append(root.left.val) temp_stack.append(root.left) if root.right: temp_list.append(root.right.val) temp_stack.append(root.right) if temp_list: list_out.append(temp_list) self.Zprint(list_out, temp_stack) def Print(self, pRoot): # write code here list_out = [] stack = [] if pRoot: list_out.append([pRoot.val]) stack.append(pRoot) self.Zprint(list_out,stack) return list_out
