v1 – 循环遍历
思路:这道题需要遍历整个树,并且需要把深度信息存入,用来构建答案的嵌套关系。在这里我们使用depth来记录深度,使用res存储结果。
class Solution:
def Print(self , pRoot: TreeNode) -> List[List[int]]:
# write code here
stack = []
depth = 0
stack.append([pRoot,0])
res = []
while stack:
root, depth = stack.pop(0)
if root:
# print(root.val, depth)
if len(res) == depth:
res.append([root.val])
else:
res[depth].append(root.val)
stack.append([root.left, depth+1])
stack.append([root.right, depth+1])
return res