-
Notifications
You must be signed in to change notification settings - Fork 0
/
Recover-Binary-Search-Tree.cpp
89 lines (68 loc) · 1.72 KB
/
Recover-Binary-Search-Tree.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* Song Qiang <qiang.song@usc.edu> 2013
*
*/
/*
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note: A solution using O(n) space is pretty straight forward. Could
you devise a constant space solution?
confused what "{1,#,2,3}" means? > read more on how binary tree is
serialized on OJ.
*/
#include <cmath>
#include <cassert>
#include <vector>
#include <numeric>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <limits>
#include <utility>
using namespace std;
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void
findbadnodes(TreeNode* r, TreeNode* &prev, vector<TreeNode*> &badnodes)
{
if (r->left != NULL && badnodes.size() < 4)
findbadnodes(r->left, prev, badnodes);
if (prev != NULL && prev->val > r->val)
{
badnodes.push_back(prev);
badnodes.push_back(r);
}
prev = r;
if (r->right != NULL && badnodes.size() < 4)
findbadnodes(r->right, prev, badnodes);
}
void
recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<TreeNode*> badnodes;
TreeNode* prev = NULL;
findbadnodes(root, prev, badnodes);
swap(badnodes.front()->val, badnodes.back()->val);
}
};
int
main(int argn, char** argv)
{
Solution s;
}