Given the root of a binary tree, extract the leftmost and rightmost nodes of each level. If a level contains only one node, that node is considered both the leftmost and rightmost node, but its value should only be included once in the result for that level. Return a single flattened list of the values of these extreme nodes ordered level by level from top to bottom, with the order of values within each level's extremes alternating: for even-indexed levels (0, 2, 4...), list the leftmost node's value first, then the rightmost node's value (if distinct); for odd-indexed levels (1, 3, 5...), list the rightmost node's value first, then the leftmost node's value (if distinct).
Explanation: Level 0 (even): Nodes are [1]. Extremes in left-to-right order: [1]. Level 1 (odd): Nodes are [2, 3]. Extremes in right-to-left order: [3, 2]. Level 2 (even): Nodes are [4, 5, 6]. Extremes in left-to-right order: [4, 6]. Combining these gives [1, 3, 2, 4, 6].
Explanation: Level 0 (even): [1] -> extremes: [1]. Level 1 (odd): [2] -> extremes: [2]. Level 2 (even): [3] -> extremes: [3]. Level 3 (odd): [4] -> extremes: [4]. Combining these yields [1, 2, 3, 4].
Master coding challenges related to Trees and solve the Zigzag Level Extremes problem optimally.
No dry run loaded.
🚀 Practice this problem
Run code, get AI hints & track streak