All problems
0402EasyTreeDepth-First SearchBreadth-First SearchBinary Tree

Mirror The Splitter Harness

Tracked in this browser only
Write code

Trains the technique from

LeetCode 226Invert Binary Tree

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A cable installer describes a broadcast harness as a binary tree of splitters, where each splitter has a left feed and a right feed and either may be absent.

The harness arrives as a level-order list root. Its first entry is the value at the top splitter. After that, every splitter that is present contributes its left feed and then its right feed, with null written for a feed that is absent. Nothing below an absent feed is listed, and null entries at the very end of the list are trimmed off. An empty harness is the empty list.

Rewire the harness so that at every splitter the left feed and the right feed trade places, and return the rewired harness written in the same level-order form.

Perform the rewiring by swapping the two feed links on each splitter in place. Do not assemble a second harness alongside the first.

Examples

Example 1

Input
root = [8,3,10,1,6,null,14]
Output
[8,10,3,14,null,6,1]

At the top splitter, 3 and 10 trade places. Splitter 3 held feeds 1 and 6, which trade to 6 and 1. Splitter 10 held an absent left feed and 14, which trade to 14 and absent.

Example 2

Input
root = [5,null,9]
Output
[5,9]

Splitter 5 has only a right feed of 9, so after the trade 9 becomes its left feed and its right feed is absent. The trailing `null` for that absent feed is trimmed.

Example 3

Input
root = [6,null,2,3]
Output
[6,2,null,null,3]

Splitter 6 has only a right feed of 2, which becomes its left feed. Splitter 2 has only a left feed of 3, which becomes its right feed.

Example 4

Input
root = [-4]
Output
[-4]

The single splitter has two absent feeds, and trading two absent feeds changes nothing.

Example 5

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

Splitter 1 keeps only 2, which moves to its right feed. Splitter 2 keeps only 3, which likewise moves to its right feed, so the chain now leans right the whole way down.

Constraints

  • The number of splitters is in the range [0, 100].
  • -100 <= splitter value <= 100

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def invert_tree(root: list) -> list:
Java
public TreeNode invertTree(TreeNode root)
September 7
Apply