Trains the technique from
LeetCode 99Recover Binary Search TreeThis 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 card index is filed as a search tree of distinct labels: for every card, every label in its left branch is smaller than the card's own and every label in its right branch is larger.
A clerk peeled the labels off exactly two cards and stuck each one on the other card. The shape of the index was not touched, only those two labels, and the index no longer files correctly.
The index arrives as shelf, a tier-by-tier listing. shelf[0] is the root card's label. The rest of the list is consumed two entries at a time, taking cards in the order they were listed: the next two entries are that card's left-branch and right-branch labels, and null means that branch is empty, so it contributes no entries of its own. Trailing nulls are omitted.
Swap the two labels back so the index files correctly again. Exactly one pair of labels can be exchanged to achieve this. Change the labels in place in shelf -- do not build a new listing and do not move any card -- and return shelf.
Example 1
The labels 25 and 15 trade places. Afterwards 15 sits in the right branch of 10 and below 20, and 25 sits in the left branch of 30 and above 20, so every branch holds the labels it should.
Example 2
The root 2 has 3 in its left branch and 1 in its right branch. Exchanging those two labels puts the smaller one on the left and the larger one on the right.
Example 3
The root's label 8 is larger than the 5 in its right branch. Exchanging them leaves 5 at the root, with 3 on its left and 8 on its right.
Example 4
The left branch holds 2 while the root holds 1, so the two labels trade places.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def recover_tree(shelf: list) -> list:public Integer[] recoverTree(Integer[] shelf)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.