BackmediumTrees Atlassian Uber

Zigzag Level Extremes Solution

Problem Statement

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).

Example 1
Input
root = [1, 2, 3, 4, 5, null, 6]
Output
[1, 3, 2, 4, 6]

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].

Example 2
Input
root = [1, 2, null, 3, null, 4]
Output
[1, 2, 3, 4]

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].

Constraints

  • The number of nodes in the tree is in the range [0, 5 * 10^4].
  • -10^5 <= Node.val <= 10^5
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free