题解 | #把二叉树打印成多行#
把二叉树打印成多行
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=23453&ru=/exam/oj/ta&qru=/ta/coding-interviews/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D13%26type%3D13
# 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 if not pRoot: return [] queue = [] queue.append(pRoot) res2 = [] while queue: #每次开始时,先统计队列的长度,队列中原先有几个元素,用count统计出来,当count=0时,就算一行打印结束重新到队列中统计现有队列的长度,然后重新计数, count = len(queue) res=[] while count >0: root = queue.pop(0) count -= 1 if root.left: queue.append(root.left) if root.right: queue.append(root.right) res.append(root.val) res2.append(res) return res2