Recover Binary Search Tree

Pattern: Validate BST

medium

Two values of a BST were swapped. In the inorder, which should rise, the swap causes one or two drops. The first drop's bigger value and the last drop's smaller value are the swapped pair; swap them back.

The problem

Exactly two values of a BST were swapped. Fix the tree in place, without changing its shape. The function returns nothing; the tests print the tree. [1, 3, null, null, 2] becomes [3, 1, null, null, 2]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What should the inorder look like?
  • How does one swap show up in it?
  • Which two values are wrong?

Hints

    Brute force, and why it fails

    Copy the inorder, sort it, and write it back: O(n log n) time and O(n) space.

    The key insight

    A single swap leaves at most two drops in the inorder, so one walk with a prev pointer finds both nodes.

    Dry run

    30 
    21 
    12 

    [1, 3, null, null, 2]. Inorder: 3, 2, 1.

    Step 1 of 3

    The plan

    inorder walk with prev:
      if prev.val > n.val: if first is null: first = prev; second = n
    swap first.val and second.val
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    One inorder walk; Morris traversal makes it O(1) space.

    Edge cases

    • Neighbouring values swapped: one drop.
    • The root swapped.
    • Two nodes in one subtree.
    I've built my logic, show the code

    Java

    class Solution {
        private TreeNode first, second, prev;
    
        public void recoverTree(TreeNode root) {
            first = second = prev = null;
            inorder(root);
            int t = first.val; first.val = second.val; second.val = t;   // put the two back
        }
    
        private void inorder(TreeNode n) {          // the inorder should rise; the swapped pair makes it drop
            if (n == null) return;
            inorder(n.left);
            if (prev != null && prev.val > n.val) {
                if (first == null) first = prev;    // the first drop: the bigger value is out of place
                second = n;                         // the last drop: the smaller value is out of place
            }
            prev = n;
            inorder(n.right);
        }
    }

    C++

    class Solution {
    public:
        TreeNode* first;
        TreeNode* second;
        TreeNode* prev;
    
        void recoverTree(TreeNode* root) {
            first = second = prev = NULL;
            inorder(root);
            swap(first->val, second->val);          // put the two back
        }
    
        void inorder(TreeNode* n) {                 // the inorder should rise; the swapped pair makes it drop
            if (n == NULL) return;
            inorder(n->left);
            if (prev != NULL && prev->val > n->val) {
                if (first == NULL) first = prev;    // the first drop: the bigger value is out of place
                second = n;                         // the last drop: the smaller value is out of place
            }
            prev = n;
            inorder(n->right);
        }
    };

    Python

    class Solution:
        def recoverTree(self, root) -> None:
            first = second = prev = None
    
            def inorder(n):                         # the inorder should rise; the swapped pair makes it drop
                nonlocal first, second, prev
                if n is None:
                    return
                inorder(n.left)
                if prev and prev.val > n.val:
                    if first is None:
                        first = prev                # the first drop: the bigger value is out of place
                    second = n                      # the last drop: the smaller value is out of place
                prev = n
                inorder(n.right)
    
            inorder(root)
            first.val, second.val = second.val, first.val   # put the two back

    Common mistakes

    • Taking the second value from the first drop when there are two drops.
    • Swapping nodes instead of values.

    Similar problems