【剑指offer】按之字形顺序打印二叉树(python)
思路类似于“把二叉树打印成多行”,添加一个flag,表示从左到右还是从右到左,如果是从右到左就把tmp反转添加到result里。
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def Print(self, pRoot): # write code here queue = [] result = [] queue.append(pRoot) left_to_right = True while queue: num = len(queue) tmp = [] for i in range(num): node = queue.pop(0) if node is None: continue tmp.append(node.val) queue.append(node.left) queue.append(node.right) if tmp: if left_to_right: result.append(tmp) else: tmp.reverse() result.append(tmp) left_to_right = not left_to_right return result