题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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 right_order(self , lay: list[TreeNode]): next_lay = [] now_res = [] for tmp in lay: now_res.append(tmp.val) if tmp.right: next_lay.insert(0,tmp.right) if tmp.left: next_lay.insert(0,tmp.left) return next_lay, now_res def left_order(self , lay: list[TreeNode]): next_lay = [] now_res = [] for tmp in lay: now_res.append(tmp.val) if tmp.left: next_lay.insert(0,tmp.left) if tmp.right: next_lay.insert(0,tmp.right) return next_lay, now_res def Print(self , pRoot: TreeNode) -> List[List[int]]: if not pRoot: return [] res = [] lay = [[pRoot]] i = 0 while lay: nowlay = lay.pop(0) if i%2 == 0: next_lay, now_res = self.left_order(nowlay) if next_lay: lay.append(next_lay) res.append(now_res) else: next_lay, now_res = self.right_order(nowlay) if next_lay: lay.append(next_lay) res.append(now_res) i += 1 return res