python| #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
# -*- 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 if pRoot is None: return [] if pRoot.left is None and pRoot.right is None: return [[pRoot.val]] result = [] #保存结果 tem = [pRoot] #保存每一层的节点 point = True while len(tem)>0: if point: tem_val = [x.val for x in tem] result.append(tem_val) tem2 = [] for node in tem: if node.left: tem2.append(node.left) if node.right: tem2.append(node.right) point = False tem = tem2 else: tem_val = [x.val for x in tem[::-1]] result.append(tem_val) tem2 = [] for node in tem: if node.left: tem2.append(node.left) if node.right: tem2.append(node.right) point = True tem = tem2 return result