Skip to main content

Posts

Leetcode 99: Recover Binary Search Tree

  1. Problem Summary You’re given the root of a  Binary Search Tree (BST)  in which  exactly two nodes’ values have been swapped  by mistake. The tree structure (shape, parent-child links) is unchanged, but the BST ordering property is violated. Your task:  restore the BST  by swapping the values of the two incorrect nodes back,  without changing the tree structure  (i.e., only swap node values). Input: root of a BST with exactly two nodes’ values swapped. Output: The tree corrected in-place (no return value, typically void). Constraints: Number of nodes: [2, 1000] Values: [-2 31 , 2 31 - 1] Follow-up: Solve with  O(1)  extra space (besides recursion stack). 2. Examples Explanation Example 1: Input:  root = [1,3,null,null,2] Tree: 1 left → 3 right → 2 In a correct BST, the left child of 1 must be < 1, but here it’s 3 > 1. If we swap the values of 1 and...