题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pRoot TreeNode类 # @return int整型二维数组 # from collections import deque class Solution: def Print(self , pRoot: TreeNode) -> List[List[int]]: # write code here result = [] root = pRoot if not root: return None queue = deque() queue.append(root) flag = False while queue: items = [] for i in range(len(queue)): node = queue.popleft() items.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) if flag: items = items[::-1] flag = not flag result.append(items) return result
使用一个Flag变量,每遍历完一层进行翻转,然后根据这个变量决定正序添加当前层的结果或者负序添加当前层的结果就可以了。