99. Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode* root) {
// 采用中序遍历的思路,先得到所有节点中序遍历的结果,
// 再将中序遍历的结果排序即可得到
if (root) {
vector<TreeNode*> vec;
TreeNode* p = root;
stack<TreeNode*> sta;
while(p || !sta.empty()) {
if (p) {
sta.push(p);
p = p -> left;
} else {
vec.push_back(sta.top());
p = sta.top() -> right;
sta.pop();
}
}
int size = vec.size();
for (int i = 0; i < size -1; i++) {
for (int j = i + 1; j < size; j++) {
if (vec[i] -> val > vec[j] -> val) {
int temp = vec[i] -> val;
vec[i] -> val = vec[j] -> val;
vec[j] -> val = temp;
}
}
}
}
}
};