Ninja technique🥷 to ACE DSA Interviews.
class Solution {
public:
TreeNode *firstNode, *secondNode, *prevNode;
void recoverTree(TreeNode* root)
{
inorder(root);
// swap the values of misplaced nodes
swap(firstNode->val, secondNode->val);
}
void inorder(TreeNode* root)
{
if (root == NULL) return;
inorder(root->left);
if (prevNode!=NULL && root->val < prevNode->val) {
// set first node
if (firstNode == NULL) firstNode = prevNode;
// set/update second node
secondNode = root;
}
// update previous node
prevNode = root;
inorder(root->right);
}
};