leetcode103 Binary Tree Zigzag Level Order Traversal
Posted yawenw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode103 Binary Tree Zigzag Level Order Traversal相关的知识,希望对你有一定的参考价值。
1 """ 2 自己AC 3 为了实现Z字形遍历 4 记录了二叉树的depth,如果depth为2的倍数 5 将得到的值reverse()处理一下再存入res中 6 """ 7 8 class TreeNode: 9 def __init__(self, x): 10 self.val = x 11 self.left = None 12 self.right = None 13 14 class Solution: 15 def zigzagLevelOrder(self, root): 16 if not root: 17 return [] 18 res = [] 19 queue = [] 20 queue.append(root) 21 depth = 1 22 while queue: 23 cur = [] 24 for x in queue: 25 cur.append(x.val) 26 if depth % 2 == 0:#bug 写进for循环里了 27 cur.reverse() 28 res.append(cur) 29 newqueue = [] 30 for x in queue: 31 if x.left: 32 newqueue.append(x.left) 33 if x.right: 34 newqueue.append(x.right) 35 queue = newqueue 36 depth += 1 37 return res
以上是关于leetcode103 Binary Tree Zigzag Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 103. Binary Tree Zigzag Level Order Traversal
[LeetCode]题解(python):103 Binary Tree Zigzag Level Order Traversal
#Leetcode# 103. Binary Tree Zigzag Level Order Traversal
[leetcode tree]103. Binary Tree Zigzag Level Order Traversal