Article Directory
topic
Given a binary tree, return the zigzag hierarchical traversal of its node values. (That is, the next layer is traversed from left to right, then from right to left, and so on, alternating between layers).
For example: Given a binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
The zigzag sequence is returned as follows:
[ [3], [20,9], [15,7] ]
Problem-solving ideas
BFS
The stack is used for normal layer sequence traversal, that is, each traversal is traversed from left to right, but when recording the value, it is added to determine whether to record from left to right or traverse from right to left.
Code
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root :
return []
stack = [root]
n = []
n_val = []
start = -1
ans = [[root.val]]
while stack:
cur = stack.pop(0)
if cur.left:
n.append(cur.left)
n_val.append(cur.left.val)
if cur.right:
n.append(cur.right)
n_val.append(cur.right.val)
if not stack:
stack = n
if start == -1 and n_val:
ans.append(n_val[::-1])
elif n_val:
ans.append(n_val)
n_val = []
n = []
start = -start
return ans