Problem
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
1 |
|
return its zigzag level order traversal as:
1 |
|
Explanation 1
-
Similar to 102. Binary Tree Level Order Traversal, but this time we need to add value from left to right, in the next level, we add values from right to left. Then next level, add values from left to right, next level from right to left.
-
When the current level is from left to right, we can normally pop value from the beginning and add its child to the end (left child first). When the current level is from right to left, we pop values from the end and add its child (right child first) to the beginning.
Solution 1
1 |
|
Explanation 2
- We can also use DFS to solve this problem. Start from level 0, if the current level is even number, then we add the current root value to the end of sublist
res[level]
, else add it to the front of the sublistres[level]
.
Solution 2
1 |
|