3
/ \
9  20
/  \
15   7

[
[3],
[20,9],
[15,7]
]

三、代码

# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> list:
res = []

def dfs(root, depth):
if root is None:
return
if depth == len(res):
res.append([root.val])
else:
if depth % 2 == 1:
depth_list = res[depth]
temp = [root.val]
temp.extend(depth_list)
res[depth] = temp
else:
res[depth].append(root.val)
dfs(root.left, depth + 1)
dfs(root.right, depth + 1)

dfs(root, 0)
return res

if __name__ == '__main__':
# a = TreeNode(3)
# a.left = TreeNode(9)
# a.right = TreeNode(20)
# a.right.left = TreeNode(15)
# a.right.right = TreeNode(7)

a = TreeNode(1)
a.left = TreeNode(2)
a.right = TreeNode(3)
a.left.left = TreeNode(4)
a.left.right = TreeNode(5)

s = Solution()
ans = s.zigzagLevelOrder(a)
print(ans)

03-15 564
03-14 348

03-24 404
07-17 972
05-31 432
09-19 1010
08-19 469
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。