aboutsummaryrefslogtreecommitdiff
path: root/recover_BST.cpp
blob: 9120825624c1a3b49bd67fb2b8921ddf0a33c971 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include "leetcode.h"

class Solution {
public:
  vector<pair<TreeNode *, TreeNode *>> vec;
  void recoverTree(TreeNode *root) {
    inOrder(root);
    if (vec.size() == 1)
      swap(vec[0].first->val, vec[0].second->val);
    if (vec.size() == 2)
      swap(vec[0].first->val, vec[1].second->val);
  }

private:
  TreeNode *prev = NULL;
  void inOrder(TreeNode *root) {
    if (!root)
      return;
    inOrder(root->left);
    if (prev && prev->val > root->val)
      vec.push_back({prev, root});
    prev = root;
    inOrder(root->right);
  }
};

int main() {}