This one took me a minute to even parse what they were asking.
Use Morris inorder traversal to achieve O(1) space and O(n) time without recursion or stack. During traversal, track the previous node and identify the two swapped nodes by detecting inversions. Then swap their values to restore the BST.
Pro tip: Emphasize that Morris traversal temporarily modifies the tree but restores it, ensuring O(1) space. Also, clearly distinguish between adjacent and non-adjacent swaps: adjacent swaps produce one inversion, while non-adjacent produce two.
Clarify that the BST has exactly two nodes swapped, and we must fix it in O(n) time and O(1) space without recursion or explicit stack. Recognize that we need to detect the swapped nodes via inorder traversal.
Use Morris traversal to visit nodes in inorder without extra space. For each node, if it has a left child, find the rightmost node in its left subtree and create a temporary link to the current node; otherwise, visit the node and move to the right child.
During traversal, keep track of the previous node. When current node's value is less than previous, we found an inversion. For the first inversion, set first = previous and middle = current; for the second inversion, set last = current. If only one inversion, the swapped nodes are first and middle (adjacent case); otherwise, they are first and last (non-adjacent case).
After traversal, swap the values of the two identified nodes. This restores the BST property without changing the tree structure.
Confirm that the tree is now a valid BST. Explain that Morris traversal takes O(n) time and O(1) space, and that the swap is O(1). Mention that the tree structure remains unchanged.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.