Binary Trees Breadth first: level by level
373. Binary Tree Zigzag Level Order Traversal
You are given root, the root node of a binary tree. Return the values of its nodes level by level, in a
zigzag: a list with one list for each level, from the top level down. The first level is read from left to
right, the second from right to left, the third from left to right again, and so on. The direction changes
at every level.
The root is the only node on the first level. Its children make up the second level, their children the
third, and so on. Nodes on the same level can have different parents. An empty tree has no levels, so the
answer is [].
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [5, 1, 8, -3, null, 6, 2, null, 4, 9, null, null, 7]
[[5],[8,1],[-3,6,2],[7,9,4]]Explanation: 5 is alone at the top. The second level holds 1 and 8, read from right to left as 8, 1. The third level goes left to right again: −3, 6, 2. The last level holds 4, 9 and 7, read from right to left as 7, 9, 4.
Example 2
Input: root = []
[]Explanation: The tree has no nodes, so it has no levels.
Example 3
Input: root = [-1000000000, 1000000000, -1000000000, null, 0]
[[-1000000000],[-1000000000,1000000000],[0]]Explanation: The second level holds 109 on the left and −109 on the right, so it reads −109, 109. The third level has a single node, 0.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.