Problem
A valid binary search tree had the stored values of exactly two nodes exchanged by mistake. Restore it by correcting those values, while leaving its tree structure unchanged. The final child links and node positions must match the input structure.
Use the supplied TreeNode with val, left, and right fields and retain the void mutation interface:
void recoverTree(TreeNode* root);
The examples display level-order values with null for absent children. They describe the tree after the call, not a returned replacement tree.
Examples
Input: root = [4,6,2,1,3,5,7]
Tree after call: [4,2,6,1,3,5,7]
The values 2 and 6 were exchanged; node positions do not move.
Input: root = [1,2,3]
Tree after call: [2,1,3]
Constraints
-
The tree contains between 2 and 1000 nodes.
-
Node values lie between -2147483648 and 2147483647, inclusive.
-
Exactly two node values were swapped in an otherwise valid BST.
-
Recover the values without changing the final structure.
Source follow-up
A method using O(n) space is straightforward. Can the repair use O(1) extra space?