Leetcode 99 Solution
This article provides solution to leetcode question 99 (recover-binary-search-tree)
Access this page by simply typing in "lcs 99" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/recover-binary-search-tree
Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
TreeNode* first;
TreeNode* second;
TreeNode* prev;
public:
void inorder(TreeNode* root)
{
if (root == NULL)
return;
inorder(root->left);
if (prev)
{
if (prev->val > root->val)
{
if (first == NULL)
first = prev;
second = root;
}
}
prev = root;
inorder(root->right);
}
void recoverTree(TreeNode* root) {
first = second = prev = NULL;
inorder(root);
if (first && second)
swap(first->val, second->val);
}
};