题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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整型二维数组 # 此题为非常经典的双端队列的应用 class Solution: def Print(self , pRoot: TreeNode) -> List[List[int]]: # write code here from collections import deque if not pRoot: return [] res = [] DQ = deque([pRoot]) level = 1 # 控制左右交替运行 length = 1 while DQ: # 正常流程队列的层次遍历 level_res = [] for _ in range(length): if level % 2 == 0: # 要点在这,如果从左侧出队,那么左右子从右侧入队,顺序为先右后左 cur = DQ.popleft() if cur.right: DQ.append(cur.right) if cur.left: DQ.append(cur.left) else:# 如果从右侧出队,则左右子就要从左侧入队,顺序为先左后右 cur = DQ.pop() if cur.left: DQ.appendleft(cur.left) if cur.right: DQ.appendleft(cur.right) level_res.append(cur.val) # 存层次 level += 1 # 左右交替 res.append(level_res) length = len(DQ) return res