题目
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Follow up:
A solution using O(n) space is pretty straight forward.
Could you devise a constant space solution?
原题链接:https://leetcode.com/problems/recover-binary-search-tree/
思路
中序遍历二叉排序树可以得到一个递增序列,将序列出现的元素从小到大进行排序,与中序遍历的结果进行对比,并找出不同的两个值,再到二叉树中找出对应的结点进行修改
代码
/**
* 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) {
return;
}
vector<int> list;
inorderTree(root, list);
vector<int> standard(list);
for (int i = 0; i < standard.size() - 1; ++i) {
for (int j = standard.size() - 1; j > i; --j) {
if (standard[j] < standard[j - 1]) {
int tmp1 = standard[j];
standard[j] = standard[j - 1];
standard[j - 1] = tmp1;
}
}
}
vector<int> diffVal;
for (int i = 0; i < list.size(); ++i) {
if (list[i] != standard[i]) {
diffVal.push_back(list[i]);
}
}
TreeNode* p = NULL;
getVal(root, diffVal[0], p);
TreeNode* q = NULL;
getVal(root, diffVal[1], q);
int tmp = p->val;
p->val = q->val;
q->val = tmp;
}
void inorderTree(TreeNode* node, vector<int> &list) {
if (!node) {
return;
}
if (node->left) {
inorderTree(node->left, list);
}
list.push_back(node->val);
if (node->right) {
inorderTree(node->right, list);
}
}
void getVal(TreeNode* root, int val, TreeNode* &res) {
if (root->val == val) {
res = root;
return;
}
if (root->left) {
getVal(root->left, val, res);
}
if (root->right) {
getVal(root->right, val, res);
}
}
};