Problem · Tree
Recover Binary Search Tree
Learn this problemProblem statement
You are given the root of a binary search tree in which the values of exactly two nodes were swapped by mistake. Restore the binary search tree without changing its structure.
The callable returns the same root after recovery so the judge can serialize and compare the corrected tree.
Function
recoverTree(root: TreeNode) → TreeNodeExamples
Example 1
root = [1,3,null,null,2]return = [3,1,null,null,2]The value 3 cannot be the left child of 1 in a valid binary search tree. Swapping 1 and 3 restores the ordering.
Example 2
root = [3,1,4,null,null,2]return = [2,1,4,null,null,3]The inorder sequence is [1,3,2,4]. Swapping the misplaced values 3 and 2 makes it increasing.
Example 3
root = [2,3,1]return = [2,1,3]The two child values are reversed. Swapping them preserves the three-node structure and restores the tree.
Constraints
- The tree contains between
2and1000nodes. -2^31 <= Node.val <= 2^31 - 1- The input was a valid binary search tree before exactly two node values were exchanged.