标签:turn roo binary etc reverse self root one 记录
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
标签:turn roo binary etc reverse self root one 记录
原文地址:https://www.cnblogs.com/yawenw/p/12375454.html