Back to DSA

Recover Binary Search Tree

hard
Acceptance: 40%
BSTBinary Tree

Two nodes in a binary search tree have had their values accidentally swapped, violating the BST property. Identify the two misplaced nodes and swap their values back to restore the tree, keeping the tree structure unchanged.

Examples

Example 1:
Input:root = [5,1,null,null,4]
Output:[5,4,null,null,1]
Example 2:
Input:root = [2,4,1]
Output:[2,1,4]

Hints

00:00
1234567