Skip to content

Latest commit

 

History

History

99

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2

Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

Follow up:

  • A solution using O(n) space is pretty straight forward.
  • Could you devise a constant space solution?

Related Topics:
Tree, Depth-first Search

Solution 1. DFS

DFS to find the minimal incorrect node a and the maximum incorrect node b, and swap them in the end.

In DFS, we use left and right to point to the left and right bound nodes respectively.

  • If root->val is smaller than left->val, root, left is an incorrect pair.
  • If root->val is greater than right->val, right, root is an incorrect pair.
// OJ: https://leetcode.com/problems/recover-binary-search-tree/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
    TreeNode *a = NULL, *b = NULL;
    void update(TreeNode *x, TreeNode *y) {
        if (!a || x->val < a->val) a = x;
        if (!b || y->val > b->val) b = y;
    }
    void dfs(TreeNode *root, TreeNode *left = NULL, TreeNode *right = NULL) {
        if (!root) return;
        if (left && left->val > root->val) update(root, left);
        if (right && right->val < root->val) update(right, root);
        dfs(root->left, left, root);
        dfs(root->right, root, right);
    }
public:
    void recoverTree(TreeNode* root) {
        dfs(root);
        swap(a->val, b->val);
    }
};