[InterviewBit] Recover Binary Search Tree

Recover Binary Search Tree

  • Time : O(n)
  • Space : O(1)
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
28
29
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

void dfs(TreeNode* A, int& small, vector<int>& res) {
if(A == NULL) return;
dfs(A->left, small, res);
if(small > A->val) {
if(res.empty()) {
res.push_back(small);
res.push_back(A->val);
} else res.back() = A->val;
}
small = A->val;
dfs(A->right, small, res);
}
vector<int> Solution::recoverTree(TreeNode* A) {
vector<int> res;
int small = INT_MIN;
dfs(A,small,res);
sort(begin(res),end(res));
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/01/PS/interviewbit/recover-binary-search-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.