Leetcode 99: Recover Binary Search Tree

grid47
grid47
Exploring patterns and algorithms
Oct 28, 2024 5 min read

A tree softly rearranging its nodes, finding its balance and order.
Solution to LeetCode 99: Recover Binary Search Tree Problem

You are given the root of a binary search tree (BST), but two nodes in the tree were swapped by mistake. Your task is to recover the tree by swapping the two nodes back, without changing the structure of the tree.
Problem
Approach
Steps
Complexity
Input: The input consists of the root node of a binary search tree.
Example: Input: root = [2, 4, 3, 1]
Constraints:
• The tree contains between 2 and 1000 nodes.
• -2^31 <= Node.val <= 2^31 - 1
Output: Return the root of the binary search tree after recovering the swapped nodes.
Example: Output: [3, 4, 2, 1]
Constraints:
• The function should return the corrected BST.
Goal: The goal is to identify the two swapped nodes and swap them back to restore the BST's validity.
Steps:
• Perform an inorder traversal of the tree while keeping track of the previously visited node.
• Identify the two nodes that are out of order during the traversal.
• Once both swapped nodes are found, swap their values to restore the tree.
Goal: The input tree contains between 2 and 1000 nodes, and node values are within the 32-bit signed integer range.
Steps:
• The number of nodes in the tree is between 2 and 1000.
• Node values are within the range of [-2^31, 2^31 - 1].
Assumptions:
• The binary tree is a valid BST, except for the two swapped nodes.
Input: Input: root = [2, 4, 3, 1]
Explanation: In this case, nodes 2 and 4 were swapped, so swapping them back will restore the binary search tree to [3, 4, 2, 1].

Input: Input: root = [3, 1, 4, null, null, 2]
Explanation: Here, nodes 2 and 3 were swapped. Swapping them back restores the binary search tree to [2, 1, 4, null, null, 3].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus