937. Recover BST — O(1) Space Morris

HardTreesBSTMorris TraversalInorder

Given the root of a binary search tree in which exactly two nodes' values were swapped by mistake, recover the tree by swapping the two values back, using O(1) extra space via Morris inorder traversal (no recursion or stack). Return the corrected tree as a level-order array. The tree is given as a level-order array.

Input: A level-order array of the tree.

Output: Array — the corrected BST in level order.

Examples

Example 1
Input: [1,3,null,null,2]
Output: [3,1,null,null,2]
Explanation: Swap 1 and 3.
Example 2
Input: [3,1,4,null,null,2]
Output: [2,1,4,null,null,3]
Explanation: Swap 3 and 2.
Example 3
Input: [2,1,3]
Output: [2,1,3]
Explanation: Already valid.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →