又有好几天没有做题,这道题看了题目很久了,一直在思考,因为要求常数空间而实际上递归解法需要的空间并不是常数级别的。看到网上的解答,有人说可以用Morris方法遍历二叉树,这样可以在o(1)空间复杂度和o(n)时间复杂度完成二叉树的遍历。但是好几天没有刷题了,想要快点做出这道题,所以还是用了递归的解法。Morris方法下次再做吧~
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.
Have you met this question in a real interview?
Yes
No
题目地址:https://oj.leetcode.com/problems/recover-binary-search-tree/
解题思路:思路是先得到二叉树的中序遍历,找出顺序不对的数,如果只有一个地方顺序不对交换两个数;如果出现两个顺序不对的地方,把第一个地方的较大的数和第二个地方较小的数交换。用change这个vector来存储顺序不对的节点。不管最后change中是只有两个节点还是有4个节点,都是交换第一个节点和最后一个节点的值。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *pre;
vector<TreeNode *> change;
void recoverTree(TreeNode *root) {
//思路是先得到二叉树的中序遍历,找出顺序不对的数,如果只有一个地方顺序不对交换两个数;如果出现两个顺序不对的地方,把第一个地方的较大的数和第二个地方较小的数交换
if(root==NULL) return;
if(root->left==NULL&&root->right==NULL) return;
pre=NULL;
change.clear();
inorder(root);
//交换change第一个节点和最后一个节点的值
if(change.size()>0){
int tmp=change[0]->val;
change[0]->val=change[change.size()-1]->val;
change[change.size()-1]->val=tmp;
}
}
void inorder(TreeNode *root){
if(root == NULL) return;
inorder(root->left);
if(pre == NULL){
pre = root;
}else{
if(pre->val>root->val){
change.push_back(pre);
change.push_back(root);
}
pre = root;
}
inorder(root->right);
}
};