Restore a BST after Two Stored Values Were Exchanged

Quick Overview

Repair exactly two exchanged BST node values without changing the final tree structure, including a constant-space follow-up.

Restore a BST after Two Stored Values Were Exchanged

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### 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: ```cpp 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 ```text 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. ```text 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?

Overview: Repair exactly two exchanged BST node values without changing the final tree structure, including a constant-space follow-up.

Amazon logo
Amazon
Source window: 0–3 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

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?