# 【leetcode】103:二叉树的锯齿形层序遍历

这个题目和leetcode102的题目非常类似，我们只需要对leetcode102的代码稍作修改就可以得到最终的答案了，我们来看看leetcode102的代码：

class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: return []
res = []
queue = [root]
while queue:
tmp = []
for _ in range(len(queue)):
node = queue.pop(0)
tmp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(tmp)
return res

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: return []
res = []
queue = [root]
i=0
while queue:
tmp = []
for _ in range(len(queue)):
node = queue.pop(0)
tmp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if i%2==0:
res.append(tmp)
else:
tmp.reverse()
res.append(tmp)
i+=1
return res

posted @ 2021-10-11 21:52  Geeksongs  阅读(6)  评论(0编辑  收藏  举报