AcWing 45. 之字形打印二叉树, python 递归实现
原题链接
中等
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def printFromTopToBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
def dfs(root, depth, res):
if not root:
return
if depth == len(res):
res.append([])
if depth % 2 == 1:
res[depth].insert(0, root.val)
else:
res[depth].append(root.val)
dfs(root.left, depth+1, res)
dfs(root.right, depth+1, res)
if not root:
return []
res = [[]]
dfs(root, 0, res)
return res