Problem 747
Recover a Binary Search Tree
Hard · 30 pts · Tree, Binary Search Tree, Depth-First Search
Problem
The values of exactly two nodes of a binary search tree with distinct values were swapped by mistake. Fix the tree by swapping those two values back, without changing its shape, and print it in level order. An in-order traversal of a correct BST is increasing; with two values swapped it has one or two places where a value is followed by a smaller one. The first wrong node is the larger value at the first drop, and the second is the smaller value at the last drop.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode. The tree is a BST with exactly two values swapped.
Output
Print the corrected tree as level-order tokens separated by spaces, using null for missing children and without trailing nulls.
Constraints
2 <= number of nodes <= 1000; values are distinct
Example input
5 1 3 null null 2
Example output
3 1 null null 2
Explanation
In the tree 1 3 null null 2, the in-order sequence is 3 2 1 instead of increasing. Swapping 1 and 3 back gives 3 1 null null 2, whose in-order sequence is 1 2 3.