您的位置:首页 > 其它

99. Recover Binary Search Tree(难)

2016-09-01 23:16 513 查看
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?

Subscribe to see which companies asked this question
有两种情况,如果是中序遍历相邻的两个元素被调换了,
很容易想到就只需会出现一次违反情况,只需要把这个两个节点记录下来最后调换值就可以;
如果是不相邻的两个元素被调换了,举个例子很容易可以发现,会发生两次逆序的情况,那么这时候需要调换的元素应该是第一次逆序前面的元素,和第二次逆序后面的元素。比如1234567,1和5调换了,会得到5234167,逆序发生在52和41,我们需要把4和1调过来,那么就是52的第一个元素,41的第二个元素调换即可。

/**
* 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 == NULL) return;
TreeNode* pre = NULL;
vector<TreeNode*> res;
dfs(root, pre, res);
if (!res.empty()){
swap(res[0]->val, res[1]->val);
}
}
void dfs(TreeNode* root, TreeNode* &pre, vector<TreeNode*> &res){
if (root == NULL) return;
dfs(root->left, pre, res);
if (pre != NULL&&pre->val > root->val){
if (res.empty()){
res.push_back(pre);
res.push_back(root);
}
else{
res[1] = root;
}
}
pre = root;
dfs(root->right, pre, res);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: