Title Description
Given a binary tree, the node returns the value of its level zigzag traversal. (I.e., start right left, then right to left for the next traverse floor, and so on, alternating between the layers).
For example: given binary tree [3,9,20, null, null, 15,7 ],
returns a zigzag traverse the level as follows: [[3], [20, 9], [15, 7]]
Algorithm thinking
Similar binary tree hierarchy traversal.
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:return []
q = [root]
result = []
k=-1
while q:
res,d= [],[]
k+=1
while q:
i=q.pop()
res.append(i.val)
if not k%2:
if i.left:d.append(i.left)
if i.right:d.append(i.right)
else:
if i.right:d.append(i.right)
if i.left:d.append(i.left)
result.append(res)
q=d[:]
return result
Or only the result of the position result.append(res)
changes.
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:return []
q = [root]
result = []
k=0
while q:
res= []
k+=1
for i in range(len(q)):
i=q.pop(0)
res.append(i.val)
if i.left:q.append(i.left)
if i.right:q.append(i.right)
if not k%2:res.reverse()
result.append(res)
return result