99. Recover Binary Search Tree
You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Example 1:
Input: root = [1,3,null,null,2]
Output: [3,1,null,null,2]
Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.
Example 2:
Input: root = [3,1,4,null,null,2]
Output: [2,1,4,null,null,3]
Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.
Constraints:
- The number of nodes in the tree is in the range [2, 1000].
- − 2 31 < = N o d e . v a l < = 2 31 − 1 -2^{31} <= Node.val <= 2^{31} - 1 −231<=Node.val<=231−1
From: LeetCode
Link: 99. Recover Binary Search Tree
Solution:
Ideas:
- inorderTraversal function performs an in-order traversal of the tree, keeping track of the previous node (prev). It identifies the first and second nodes that are out of order (first and second).
- recoverTree function calls inorderTraversal to identify the two nodes and then swaps their values.
- newTreeNode are helper functions for creating and printing the tree, respectively.
Code:
void inorderTraversal(struct TreeNode* root, struct TreeNode** prev, struct TreeNode** first, struct TreeNode** second) {
if (root == NULL) return;
// Traverse left subtree
inorderTraversal(root->left, prev, first, second);
// Process current node
if (*prev && (*prev)->val > root->val) {
if (*first == NULL) {
*first = *prev;
}
*second = root;
}
*prev = root;
// Traverse right subtree
inorderTraversal(root->right, prev, first, second);
}
void recoverTree(struct TreeNode* root) {
struct TreeNode *prev = NULL, *first = NULL, *second = NULL;
// Perform in-order traversal to find the two nodes
inorderTraversal(root, &prev, &first, &second);
// Swap the values of the two nodes
if (first && second) {
int temp = first->val;
first->val = second->val;
second->val = temp;
}
}
// Helper function to create a new tree node
struct TreeNode* newTreeNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}