75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

99. Recover Binary Search Tree

Recursive - using inorder traversal

Code

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);
    }
};